For example, in this piece of code, if line [a] is commented out, the output is 0.
inh2.cpp
#include<iostream>
using namespace std;
class A {
public:
int x;
A() { x = 10; }
};
class B : public A {
public:
int x; // <--------- [a]
B() { x = 0; }
};
int main() {
A* ab = new B;
cout << ab->x << endl;
}
results from gcc
$ g++ inh2.cpp
$ ./a.out
10
$
I have two questions:
- How does
ab->xresolve to10in the above case? The object is of typeclass B, and thus should value to0. - Why does commenting
Line [a]change the behaviour of the code? My reasoning is thatxwould have anyways been inherited, which should result in same behaviour.
My reasoning for Q #1 above:
-
abpoints to the memory location of an object ofclass B. It is a physical object in the sense that all the variables with their values are assigned memory. -
Variable
xwithin this object stores value0. -
When
ab->xis done, ab tells us the memory location of the object, and we go look inside it to find that x is 0. So we should print 0.
Where am I wrong here?
Yes, it is of type
B, but you are assigning it as a pointer to anA, and therefore it is using thexdefined on A (as when we’re dealing with a pointer to A, we don’t know thatBeven exists, even though that’s what you allocated).When you comment out the line, during the construction phase,
As constructor is called first, thenBs constructor, which setsx(in its base class) to 0. There is only onexat this point, and Bs constructor is called last.