Ohad
Ohad

Reputation: 1651

order of constructor - chain inheritance

I run the program below and after the first line of main I got this output:

1
6
1
6
13

Could anyone explain why it enters the constructors of Grand and Father twice?

//base class 
class Grand{
public:
    Grand(){cout<<"1"<<endl;}
    Grand(const Grand & g){cout<<"2"<<endl;}
    virtual ~Grand  (){cout<<"3"<<endl;}
    virtual void fun1(Grand g){cout<<"4"<<endl;}
    virtual void fun3(){cout<<"5"<<endl;}
private:
    int m_x;
    };



//derived class 
    class Father: public Grand{
    public:
        Father(){cout<<"6"<<endl;}
        Father(const Father & f){cout<<"7"<<endl;}
        ~Father(){cout<<"8"<<endl;}
        void fun1(){cout<<"9"<<endl;}
        void fun2(Father & f){
            cout<<"10";
            f.fun3();
        }
        void fun3(){
            cout<<"11"<<endl;
        }
        virtual void fun4(){
            cout<<"12"<<endl;
        }
    };


sing namespace std;

//derived class 
        class Son: public Father{
        public:
            Son(){cout<<"13"<<endl;}
            Son(const Son& s){cout<<"14"<<endl;}
            ~Son(){cout<<"15"<<endl;}
            void fun3(){cout<<"16"<<endl;}
            virtual void fun5(Son& s){
                cout<<"17"<<endl;
                s.fun1();
            }
        private:
            Father m_f;
            };

int main(){
Grand * pGrand= new Son; 
.........
.........
}

Upvotes: 2

Views: 702

Answers (1)

Puppy
Puppy

Reputation: 147054

Because you both inherited from Father and instantiated a member of type Father, so now Son has two Father objects- the direct base, and a member.

Upvotes: 9

Related Questions