Initialization of virtual bases

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Theese

    Initialization of virtual bases

    Hello all,

    The code example below has proper behavior (of course), but I'm trying to
    understand how the behavior is brought about. Specifically, what happens to
    B's and C's initialization of A??? Is it just ignored even though it
    explicitly appears in the code?

    Thanks,
    Dave

    #include <iostream>

    using namespace std;

    class A
    {
    public:
    A(int d): data(d)
    {
    cout << "data initialized to " << d << endl;
    }

    private:
    int data;
    };

    class B: virtual public A
    {
    public:
    B(int d): A(d)
    {
    }
    };

    class C: virtual public A
    {
    public:
    C(int d): A(d)
    {
    }
    };

    class D: public B, public C
    {
    public:
    D(int d): A(d), B(d + 1), C(d + 2)
    {
    }
    };

    int main(void)
    {
    // Displays "data initialized to 1"
    D foo(1);

    return 0;
    }



  • John Harrison

    #2
    Re: Initialization of virtual bases


    "Dave Theese" <cheeser_1998@y ahoo.com> wrote in message
    news:QSX1b.7781 $QT5.1646@fed1r ead02...[color=blue]
    > Hello all,
    >
    > The code example below has proper behavior (of course), but I'm trying to
    > understand how the behavior is brought about. Specifically, what happens[/color]
    to[color=blue]
    > B's and C's initialization of A??? Is it just ignored even though it
    > explicitly appears in the code?
    >
    > Thanks,
    > Dave
    >
    > #include <iostream>
    >
    > using namespace std;
    >
    > class A
    > {
    > public:
    > A(int d): data(d)
    > {
    > cout << "data initialized to " << d << endl;
    > }
    >
    > private:
    > int data;
    > };
    >
    > class B: virtual public A
    > {
    > public:
    > B(int d): A(d)
    > {
    > }
    > };
    >
    > class C: virtual public A
    > {
    > public:
    > C(int d): A(d)
    > {
    > }
    > };
    >
    > class D: public B, public C
    > {
    > public:
    > D(int d): A(d), B(d + 1), C(d + 2)
    > {
    > }
    > };
    >
    > int main(void)
    > {
    > // Displays "data initialized to 1"
    > D foo(1);
    >
    > return 0;
    > }
    >[/color]

    Yes I believe so, virtual base classes are initialised by the more derived
    object (or something like that). So if you created a B or a C object then B
    or C would be responsible for initialising A.

    john


    Comment

    Working...