guitar_geek
guitar_geek

Reputation: 498

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 ?

Upvotes: 2

Views: 116

Answers (4)

Brandon Kohn
Brandon Kohn

Reputation: 1621

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{...

Upvotes: 6

David Heffernan
David Heffernan

Reputation: 613262

By default, class inheritance is private. And so:

class Der3: public Der1, Der2

is the same as:

class Der3: public Der1, private Der2

You need to use public inheritance for both base classes:

class Der3: public Der1, public Der2

Upvotes: 3

D Stanley
D Stanley

Reputation: 152596

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.

Upvotes: 4

James Curran
James Curran

Reputation: 103535

class Der3:public Der1,Der2 {

The 'public' there is only good for the next base class. You want to write:

class Der3: public Der1, public Der2 {

Also, it should be noted that this example also shows the deadly "diamond" inherience pattern, so it's designer clearly should be slapped.

Upvotes: 3

Related Questions