I'm so confused with the output of the following code:
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : x(2) { }
virtual ~Parent() { }
void NonVirtual() { cout << "Parent::NonVirtual() x = " << x << endl; }
private:
int x;
};
class Child : public Parent
{
public:
Child() : x(1) { }
virtual ~Child() { }
void NonVirtual() { cout << "Child::NonVirtual() x = " << x << endl; }
private:
int x;
};
int main()
{
Child c;
Parent* p = &c;
c.NonVirtual(); // Output: Child::NonVirtual() x = 1
p->NonVirtual(); // Output: Parent::NonVirtual() x = 2
// Question: are there two x'es in the Child object c?
// where is x = 2 from (we have not defined any Parent object)?
cout << sizeof(c) << endl;
cout << sizeof(*p) << endl;
return 0;
}