Kevin Dong
Kevin Dong

Reputation: 5351

Confused about C++ inheritance

Code snippet:

class A
{
    protected:
    int b;
};

class B : public A
{

};

struct C : B
{
    int call (const C&);
};

class D : B
{
    int call (const C&);
};

int C::call (const C& c)
{
    return c.b;
}

int D::call (const C& c)
{
    return c.b;
}

int main (void)
{
    return 0;
}

Why c.b can be accessed in C::call() but not in D::call()?

Don't they the same? Both of them are referenced from the outside!

Here is the error message GCC compiler gives:

main.cpp: In member function 'int D::call(const C&)':
main.cpp:4:9: error: 'int A::b' is protected
     int b;
         ^
main.cpp:29:14: error: within this context
     return c.b;
              ^

Upvotes: 0

Views: 130

Answers (1)

Christophe
Christophe

Reputation: 73366

Your inheritance tree is the following: enter image description here

So C is a B which is itself an A. As b is protected, C and B can access the b they've inherited from A.

Similarly, D is a B which is itself an A. So D and B can access the b they've inherited from A.

However C and D are not directly related. They are like strangers for another. So C cannot see the b from a D, nor can a D see the b from a C.

Looking at your code:

First, in the following code, you don't return the b member of the object. You return the b of another C object that you pass as parameter:

int C::call (const C& c)
{
    return c.b;
}

Regardles of this detail, any member functions of C has access to all the members of any C object. So this function is valid C++ code.

The next function does not work as well:

int D::call (const C& c)
{
    return c.b;
}

THe parameter passed to this member function of D is of class C. As we have seen above, C and D are not directly related. So C objects are like a black box for member functions of D. Hence the function can only access the public members of C.

THis is why you get this error message: a D object doesn't have access to protected or private members of a C object.

Upvotes: 1

Related Questions