Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explain the inheritance in the code?

there's this code :

class Base{
    public:
    void disp(){
    cout<<"base"<<endl;
    }
};

class Der1:public Base{
    public:
    void test1(){
    cout<<"der1 test1"<<endl;
    }
};

class Der2:public Base{
    public:
    void test2(){
    cout<<"der2 test2"<<endl;
    }
};

class Der3:public Der1,Der2{
    public:
    void fun(){
    cout<<"Der3 fun"<<endl;
    }
};


int main()
{
    Der3 d;
    d.test1();
}

OUTPUT: der1 test1 //printed successfully

but for

int main()
{
    Der3 d;
    d.test2();
}

it gives error that Der2 is inaccessible ...

However when i change the code to

class Base{
        public:
        void disp(){
        cout<<"base"<<endl;
        }
    };

class Der1:public Base{
    public:
    void test1(){
    cout<<"der1 test1"<<endl;
    }
};

class Der2:public Base{
    public:
    void test2(){
    cout<<"der2 test2"<<endl;
    }
};

class Der3:public Der2,Der1{  //***changed the order here*** 
    public:
    void fun(){
    cout<<"Der3 fun"<<endl;
    }
};


int main()
{
    Der3 d;
    d.test2();
}

it outputs: der2 Test2

Can someone explain what is happening here ?

like image 558
guitar_geek Avatar asked Sep 26 '26 06:09

guitar_geek


2 Answers

It should be:

class Der3:public Der2, public Der1{ 

If you don't specify the access qualifier, it defaults to private.

Also because you have a common base in the two types inherited in Der3 you should use virtual inheritance in Der1 and Der2. This avoids replicating the common Base members (if any.)

class Der1:public virtual Base{...   
class Der2:public virtual Base{...
like image 70
Brandon Kohn Avatar answered Sep 27 '26 19:09

Brandon Kohn


You have to add the accessibility to each base class:

class Der3:public Der1, public Der2{
    public:
    void fun(){
    cout<<"Der3 fun"<<endl;
    }
};

When you switch the order Der2 is a public base but Der1 is private.

like image 26
D Stanley Avatar answered Sep 27 '26 18:09

D Stanley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!