2

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?

1
  • 1
    Variables aren't treated the same way as virtual functions; they are checked at compile time. This is a consequence of the C++ Memory Model. You would have to do a cast to make this work. Commented Mar 7, 2015 at 19:23

1 Answer 1

4

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;
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.