Reputation: 3585
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?
Upvotes: 2
Views: 59
Reputation: 60218
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;
Upvotes: 3