Reputation: 330
what's wrong with the polymorphism here?
class A
{
public:
int x;
virtual void dosomething(const A& ob) = 0;
};
class B : public A
{
public:
int y;
void dosomething(const A& ob) { // I assume this will work (base class accepting a derived class by reference)
x += ob.x;
y += ob.y; // error: const class A has no memeber named 'y'
cout<<x<<" "<<y;
}
};
int main()
{
B s, m;
s.x = 3;
s.y = 9;
m.x = 3;
m.y = 9;
s.dosomething(m);
}
i tried using pointer instead of reference, and still not working
should i override the function?
Upvotes: 2
Views: 87
Reputation: 595477
dosomething()
accepts a reference to the A
portion of an object. A
does not have a member named y
, just like the compiler error says. Only B
has a y
member.
Imagine there is another class C
that also derived from A
but not B
, where C
does not have a y
member either. What do you think would happen if a C
object were passed to B::dosomething()
?
class C : public A
{
public:
int z;
void dosomething(const A& ob) { ... }
};
B b;
C c;
b.dosomething(c);
It would not work. B::dosomething()
can accept a C
object as input, but there is still no y
member for B::dosomething()
to read from.
So, you must use a type-cast inside of B::dosomething()
to check if the input obj
is actually derived from B
before accessing its y
member:
class B : public A
{
public:
int y;
void dosomething(const A& ob) {
x += ob.x;
const B *b = dynamic_cast<const B*>(&ob);
if (b) y += b->y;
cout << x << " " << y;
}
};
Upvotes: 4