-
weird output
Hi there. Could you tell me why this program's output is 49478692
Code:
#include <iostream>
using std::cout;
using std::endl;
class X {
public:
X() { }
X( int a ) : x( a ) { }
int getx() const { return x; }
private:
int x;
};
class Y : virtual public X {
public:
Y( int b ) : X( b ) { }
};
class Z : public Y {
public:
Z( int c ) : Y( c ) { }
};
int main()
{
Z zobj( 100 );
cout << zobj.getx() << endl;
getchar();
return 0;
}
while this program's
Code:
#include <iostream>
using std::cout;
using std::endl;
class X {
public:
X() { }
X( int a ) : x( a ) { }
int getx() const { return x; }
private:
int x;
};
class Y : public X {//<-just public,not virtual
public:
Y( int b ) : X( b ) { }
};
class Z : public Y {
public:
Z( int c ) : Y( c ) { }
};
int main()
{
Z zobj( 100 );
cout << zobj.getx() << endl;
getchar();
return 0;
}
is 100?
-
When deriving from a class that has a virtual base (Z derives from Y, which has X as a virtual base), the most derived constructor must initialize the virtual base.
That is, Z must initialize X either on its constructor or initialization list. What is happening is that on the first example, the x data member of the base class X is not being initialized. You are looking an the result of undefined behavior.
-