Thread: weird output

  1. #1
    csd@auth
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    71

    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?

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    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.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Weird output of scanf and printf.
    By omnificient in forum C Programming
    Replies: 2
    Last Post: 12-05-2007, 01:28 PM
  2. Output an array in a textbox
    By Diablo02 in forum C# Programming
    Replies: 5
    Last Post: 10-18-2007, 03:56 AM
  3. Connecting input iterator to output iterator
    By QuestionC in forum C++ Programming
    Replies: 2
    Last Post: 04-10-2007, 02:18 AM
  4. Trying to store system(command) Output
    By punxworm in forum C++ Programming
    Replies: 5
    Last Post: 04-20-2005, 06:46 PM
  5. Output problems with structures
    By Gkitty in forum C Programming
    Replies: 1
    Last Post: 12-16-2002, 05:27 AM