1

Code below shows base class (GrandParent) have a virtual function (show()) and two virtually derived classes (Parent1 and Parent2) with each having their own implementation of show(). Class Child inherits both Parent1 and Parent2 and implements it's own version of show().

In the code below, I have a new object (Parent2 *objP = new Child();) and calling objP->show(). I expected this to call the show() function of Parent2 (and return 9). However it is actually calling show() function of Child (and hence returning 7).

I understand that show() was virtual function of GrandParent but it is not a virtual function for Parent2. Hence confused why is objP->show() calling show() of Child and not for Parent2.

Thanks for your help.

class GrandParent {
 public:
      int virtual show() { return 10; }
};


class Parent1 : public virtual GrandParent {
 public:
      int show() { return 1; }  
};

class Parent2 : public virtual GrandParent {
 public:
      int show() { return 9; }  
};

class Child : public Parent1, public Parent2 {
 public:
      Child(){}
      int show() { return 7; }  
};

int main() {
      GrandParent *objGrand = new Child();
      GrandParent *objGrand1 = new Parent1();
      Parent2 *objP = new Child();
      Child *objChild = new Child();

      cout << objGrand->show()  << endl;// get 7 as expected
      cout << objP->show()  << endl; // get 7 instead of 9 expected
      cout << objChild->show()  << endl; // get 7 as expected
      cout << objGrand1->show()  << endl; // get 1 as expected

      return 0;
}
1
  • One note on your choice of names: There is a relation between base class and derived class and that is that a derived "is a" base. So, your child is a parent and a grandparent, but the parent is not a child. I'd avoid these very names and go with derived and base instead. Commented Jul 21, 2019 at 15:51

1 Answer 1

2

The function show() is virtual in all classes. It was declared virtual in the GrandParent base class, and all derived classes inherit that. It doesn't matter that they don't explicitly declare their overrides as virtual.

Sign up to request clarification or add additional context in comments.

4 Comments

But it would make sense to mark them override so the compiler can help you detect if you accidentally don't actually override the base class version.
And if you don't want a derived class to override a virtual function, you can mark it final.
Both valid point that could improve the original code. The point remains though, that the code works as it should, though not as expected by the OP.
Sure. I just wanted to mention those two points since I think you could improve your answer by including them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.