2
votes

I am public deriving two instances of class template 'Area', one int and another char into an separate class 'Rectangle'.

template<class T>
class Area {
  public:
    T a;
    T getArea() { return a; }
    void setArea(T t) { a = t; }
};  

class Rectangle : public Area<int>, public Area<char> {
};  

int main() {
  Rectangle a;
  a.setArea(1);
  std::cout << a.getArea() << std::endl;
  Rectangle b;
  b.setArea('c');
  std::cout << b.getArea() << std::endl;
}   

And I see ambiguity with setArea and getArea. Why is that so? I thought after public Area, public Area there would be two definitions of setArea. First, void setArea(int) and another void setArea(char). Please correct me if I am wrong. And If I am correct, why the ambiguity?

1
@AzamBham I tried using statements already. That would not work. Where do put using statements? - Hemant Bhargava
The compiler can't infer automatically which version of a.getArea() you meant to call. Try helping it: std::cout << a.Area<char>::getArea() << std::endl; - Mihai Todor
@MihaiTodor, Thanks for coming back. That also I tried and it did not work too. - Hemant Bhargava
Works for me: ideone.com/0WaMIo - Mihai Todor

1 Answers

3
votes

If you bring the name setArea from both the base classes into the derived class with using statements:

class Rectangle : public Area<int>, public Area<char> {
  using Area<int>::setArea;
  using Area<char>::setArea;
};  

the compiler will be able to call the right setArea.

This will not work for getArea as the 2 functions differ only in their return type. You will have to distinguish between them at the call site:

std::cout << a.Area<int>::getArea() << std::endl;