base class's para. const. not called from the virtual derived

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mathew1
    New Member
    • Jan 2010
    • 4

    base class's para. const. not called from the virtual derived

    Please find the below program executed in SUNOS


    Code:
    #include<iostream.h>
    
    class A
    {
    public:
    int x,y;
    A(){cout<<"\n DefaultConst A";}
    A(int i, int j){cout<<"\n Parm const A"; x=i; y=j;}
    };
    
    class B : virtual public A
    {
    public:
    int a, b;
    B():A(150,170){cout<<"\n DefaultConst B";}
    };
    
    class C: public B
    {};
    int main()
    {
    A *ptr;
    C *pobc=new C();
    pobc->a=5; pobc->b=2;
    printf("\n %d %d %d %d", pobc->x, pobc->y,pobc->a, pobc->b);
    }

    Output
    ------
    DefaultConst A
    DefaultConst B
    0 0 5 2


    Question
    ---------
    1) Why doesn't the parametrized constructor of A is being called and why x and y are being initialized with 150 and 170
    Last edited by Banfa; Jan 6 '10, 01:44 PM. Reason: Added code tags
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    Because for virtual base class default constructor is called because in "diamond pattern" there is only one instance of such base class.

    Comment

    • mathew1
      New Member
      • Jan 2010
      • 4

      #3
      Could you make me understand "diamond pattern". Atlest some hints? Thank in Advance

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        This example does not need virtual base classes.

        Virtual base classes are used only if there is a chance that a base class constructor will be called more than once during the creation of a derived object.

        For example:

        A derives from X
        B derives from X
        C derives from A and B.

        In this case, creating an object of C requires creating an object of B which requires creating an object of X. It also requires creating an object of A which requires creating an object of X. There are now two X objects inside the C object. This is the "diamond" hierarchy.

        This may be good or it may be bad depending upon your design.

        If you require a single X object you have you use virtual base classes. And when you do that, the compiler will not call any constructors. Instead, you have to call them yourself.

        So, in your example, because of that virtual base class, you need a C constructor that calls the exact constructors you need to build a C object:

        Code:
        C() : A(150, 170), B() {}
        You have to remember that virtual base classes disable the constructor calls to ancestor (indirect) base classes.

        Comment

        Working...