Reputation: 53
I am not very fluent in inheritance. I understand that if you have Class A & B that B can inherit from the code encapsulated into A, but as far as this question - I am not sure what exactly the code is saying.
The question is: Suppose you have two classes, A and B. B inherits from A. A defines only two methods, foo() (which is declared as virtual) and bar() (which is not virtual). Both methods output the letter A to the console. B also defines foo() and bar(), both of which output the letter B to the console.
What is the output of the following code?
B b;
A * pA = new A;
A * pA2 = &b;
b.foo(); b.bar();
pA ->foo(); pA->bar();
pA2->foo(); pA2->bar();
First of all, what exactly do they mean by "One is virtual, & one is not". Second question, where does the pA come from? What are they doing here? Same thing with pA2 what is that? It never mentioned pA or pA2 in the question. And finally, is &b a reference variable?
Thank you for your time.
Upvotes: 0
Views: 100
Reputation: 76240
When using pointers or references, a variable has two types: its dynamic type and its static type. The static type is the type of the pointer you are giving statically to that variable (known at compile time), while the dynamic type is the pointer type of the objects it points to.
For example assuming Dog
to be a child class of Animal
:
Animal* p = new Dog;
p
has a static type of Animal*
and a dynamic type of Dog*
. This is mostly important when dealing with the runtime type identification (RTTI).
Ok so let's analyze the code step by step:
B b;
A * pA = new A;
A * pA2 = &b;
Here we have b
which has B
as static type. pA
which has a static and dynamic type of A*
and pA2
which has a static type of A*
but a dynamic type (see virtual tables) of B*
.
b.foo();
b.bar();
Now b
is calling both of its methods. Both of which print B
to the screen (like you would normally expect (since B's function definitions hide A's).
pA->foo();
pA->bar();
Almost the same happens with the above lines. They both print A
because their static and dynamic type is A*
and their definition says they should print A
.
pA2->foo();
pA2->bar();
This is probably the most confusing part of all this. We said pA2
has a static type of A*
but a dynamic type of B*
. What does it mean?
It means that when looking for the function definition of foo
, it will actually take a look at the virtual table and find out the definition of its dynamic type (which is B*
), printing B
.
While the second call is made to a non-virtual method and therefore there's no "function virtual lookup table": the definition of the method is taken from its static type (which is A*
), printing A
.
The final output is:
B B A A B A
Upvotes: 2