This title has been used many times but after searching around 5-6 examples, I couldn’t find anything that matches my problem:
I have a simple inheritance practice.
Class A is a base class, classes B & C inherit from it:
class A {
};
class B : public A { public: int i; };
class C : public A { public: int j; };
And a class P containing overloaded functions like this:
class P
{
public:
void change(B *b)
{
b->i =1;
}
void change(C *c)
{
c->j =1;
}
};
And when I use the functions like the following:
int main()
{
A *b = new B();
A *c = new C();
P p;
p.change(b);
p.change(c);
return 0;
}
it gives an error saying:
inherit2.cpp: In function ‘int main()’:
inherit2.cpp:37:12: error: call of overloaded ‘change(A*&)’ is ambiguous
inherit2.cpp:37:12: note: candidates are:
inherit2.cpp:21:7: note: void P::change(B*) <near match>
inherit2.cpp:21:7: note: no known conversion for argument 1 from ‘A*’ to ‘B*’
inherit2.cpp:26:7: note: void P::change(C*) <near match>
inherit2.cpp:26:7: note: no known conversion for argument 1 from ‘A*’ to ‘C*’
inherit2.cpp:38:12: error: call of overloaded ‘change(A*&)’ is ambiguous
inherit2.cpp:38:12: note: candidates are:
inherit2.cpp:21:7: note: void P::change(B*) <near match>
inherit2.cpp:21:7: note: no known conversion for argument 1 from ‘A*’ to ‘B*’
inherit2.cpp:26:7: note: void P::change(C*) <near match>
inherit2.cpp:26:7: note: no known conversion for argument 1 from ‘A*’ to ‘C*’
I will appreciate if you please help me solve the problem.
rahman
With polymorphism there is no need for multiple
changemethods.