0

Consider the following code:-

#include<iostream>

using namespace std;
  
class A 
{
public:
    int a;
    A()
    {
          a = 10;
          cout<<"Address of a in A "<<&a<<endl;
    }

};
  
class B : public virtual  A {

    public:
    B()
    {
        cout<<"Address of a in B "<<&a<<endl;
    }
};
  
class C :  public virtual A {

     public:
    C()
    {
        cout<<"Address of a in C "<<&a<<endl;
    }
};


class D : public B, public C {

     public:
    D()
    {
        cout<<"Address of a in D "<<&a<<endl;
    }
};

int main()
{
  A a;
  B b;
  C c;
  D d;
    return 0;
}

So, here when we create an object of D class, Constructors are called in this order A()->B()->C()->D(). Here A() is not called again before C() because we had made use of virtual keyword, which is preventing the constructor A() to be called again.

** Question: 1 But, I wanted to know what is happening in background in code when we are using the virtual keyword?

Question 2 And is variable a in class A and class B point to same memory location?

Question 3 And why this variable's memroy address differs in class C when A is not made virtual from the address of that variable in B?**

  • Use the word "instance" instead of "class" in all your questions, i.e. instance a, vs. class A. – franji1 Mar 16 '22 at 18:43
  • "what is happening in background in code" You can always look at the generated assembly yourself. – n. m. could be an AI Mar 16 '22 at 18:45
  • [Handy reading](https://isocpp.org/wiki/faq/multiple-inheritance) – user4581301 Mar 16 '22 at 18:56
  • 1
    2. Yes, you can see that from your own output. 3. _"when A is not made virtual"_ - but it _is_ using `virtual` inheritance? Perhaps it's easier to see [like this](https://godbolt.org/z/15bGnns7P) – Ted Lyngmo Mar 16 '22 at 19:01
  • The compiler has to do some bookkeeping to keep track. The `A` subject gets constructed by the `D` constructor, so it should not get constructed by the `B` or `C` constructor. On the other hand, with an object of type `C`, the `A` subject will be constructed by the `C` constructor. – Pete Becker Mar 16 '22 at 19:37
  • Welcome to Stack Overflow! As some advice - try not to ask multiple questions as a single question. That alone is cause for closing a question, because it typically does not fit the SO format. That aside, I suspect that all of your questions are answered in the duplicates that I'm going to put at the top of this post. – Drew Dormann Mar 16 '22 at 20:48

0 Answers0