-2

Here is the code ,it is my homework using overriden methods teacher told us to analyze the code. I know the code is outputting 2, I have no clue how this code work.

public:
   int a;
   virtual void who(void) { a = 1; }
};



class B:public A{
public:
   int a;
   void who(void) { a = 2; }
};

class C :public B {
};

int main(void) {
   A x; B y; C z; A *p;
   p = &z;
   p->who();
   cout << z.a << endl;
       system("pause");
       return 0;
}



erbol meir
  • 13
  • 3
  • 2
    Please provide [mcve]. What object do you create, what methods do you call on it and what are the outputs? – Yksisarvinen May 18 '19 at 10:39
  • 1
    Then perhaps you are in need of a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Quimby May 18 '19 at 10:42
  • You have a member `a` in both `A` and `B` classes. Thus the `a` you see depend on how you access the variable. – Phil1970 May 18 '19 at 22:16

2 Answers2

1

B overrides the who() function of its parent, A. This is called polymorphism. C inherits from B, but doesn't override anything; thus, it uses all of the implementation of B. p is a pointer to an object of class A. One of the key features of class inheritance is that a pointer to a derived class is type-compatible with a pointer to its base class [1].

This means that when you call a member function of a pointer (p->who()), and the class of the object the pointer is pointing to overrides a member of its parent, is going to use the overridden member.

Sources: [1] http://www.cplusplus.com/doc/tutorial/polymorphism/

0

as long as you create a function with same input and output with name; in short: same function declaration.. the new one will be used as you refer to one which has super class that has same function. in your case; super class for C is B and it doesn't see A, but B sees A and use all functions it has except what's B declare a new implementation for.

Seif Mostafa
  • 58
  • 10