Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

Are the base constructors of virtual class from non concrete classes skipped?

I have this code:

class Base{
public:
  int x;
  Base(int x){
    this->x = x;
  }

  virtual ~Base(){
    cout<<"base destroyed"<<endl;
  }
};

class A: public virtual Base{
public:
  A(int x) : Base(x){   //is this base call here skipped?
  }

  virtual ~A(){
    cout<<"a has been destroyed"<<endl;
  }
};

class B: public A{
public:
  B():Base(10),A(12){      //initialized from here, overwrite attempt
  }
};

int main(int argc, char** argv) {
  B ey;
  cout<<ey.x<<endl;
  return 0;
}

I tried overwriting it on the concrete class's constructor initialization:

B():Base(10),A(12){ 

The output still printed 10.

Since class A isn't my concrete class, did it skip base's constructor?

A(int x):Base(x){

Upvotes: 0

Views: 89

Answers (2)

Nipun Talukdar
Nipun Talukdar

Reputation: 5387

This happens, because the Base class constructor will be called just once. It won't be called multiple times. First, the memory is allocated for the object, then Base's constructor is called, then A's constructor is called, and finally B's constructor is called. Basically, after allocating memory for the object, the inheritance tree starting from the root class is traversed and construction specific to each derived part is executed. The constructor of each class in the hierarchy will be called just once. So, only if we are modifying value of x again in A's constructor, then only the value of x changed in the object.

Upvotes: 0

T.C.
T.C.

Reputation: 137310

Virtual bases are only constructed by the constructor of the most derived class, in this case B. (They also happen to be constructed first, before any of the non-virtual direct bases of the most derived class are constructed.)

Since in your case A is not the most derived class, its constructor doesn't construct the virtual base.

Upvotes: 1

Related Questions