Pergunta

Why is "hello world" printted three times? I don't understand clearly about inheritance virtual in struct with C++.

#include<iostream>
using namespace std;

struct BS{
    BS() {
        cout << "hello world" << endl;
    }

    unsigned int color;
};

struct mid1 : virtual public BS { };
struct mid2 : virtual public BS { };
struct mid3 : public BS { };
struct mid4 : public BS { };

struct D : public mid1, public mid2, public mid3, public mid4 { };

int main() {
    D d;
    return 0;
}
Foi útil?

Solução 2

I'm stunned by the downvotes and the insulting responses.

D has four base classes. Of those, mid1 has one base class, virtual BS, and mid2 has one base class,virtual BS. There are no other uses ofvirtual BS. Somid1andmid2share one copy of aBSobject as their virtual base.mid3has a **non**-virtual base,BS; this is not shared. Andmid4has a non-virtual base, BS; this, too, is not shared. So there are three copies of BS: one that is the virtual base of mid1 and mid2, one that is the non-virtual base of mid3, and one that is the non-virtual base of mid4. Three BS objects, so three constructor calls, so three "hello world"s.

Outras dicas

Consider this example. Its more easy to understand. When you create an object of derived class the object calls the constructor of base class first and then its own constructor.

#include "stdafx.h"
#include<iostream>
#include <iomanip>
#include <conio.h>
using namespace std;

struct BaseClass{
    BaseClass() 
    {
        cout << "hello world of base class" << endl;
    }
};

struct DerivedClass1 : virtual public BaseClass { };

struct DerivedClass2 : virtual public BaseClass
{
    DerivedClass2()
    {
        cout<<"hello world of derived class"<<endl;
    }
};

int main() {

    //when you create a member of Base Class it calls just its own constructor. 
    cout<<"Creating an object of BaseClass  : "<<endl;
    BaseClass a;
    cout<<"Done \n \n";

    //when you create a member of Derived class1 it calls constructor of base class      once and then calls
    //its own constructor but as nothing is defined in its default constructor nothing      is printed.
    cout<<"Creating an object of DerivedClass1 (Pure Virtual)  : "<<endl;
    DerivedClass1 b;
    cout<<"Done \n \n";

    //when you create a member of Derived class2 it calls constructor of base class once and then calls
    //its own constructor because its derived. (See how hello world is printed twice , one for base and one for derived)
    cout<<"Creating an object of DerivedClass2  : "<<endl;
    DerivedClass2 c;
    cout<<"Done \n \n";

    getch();
    return 0;
 }

Here is the output http://codepad.org/zT3I1VMu Hope it helps!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top