Anass Anass - 1 month ago 15
C++ Question

inheritance C++ type protected

I'm getting this error in the inheritance (C++) below :

B.cpp:11:9: error: 'isMember' is a protected member of 'A'
if(x->isMember())


I've seen that a declared protected member in a "mother" class is reachable from a a member of the "daughter" class. But i still don't figure out what's the problem here.
Here is the definitions of the my two classes A and B :

#ifndef _A_H_
#define _A_H_
class A
{

private:
bool _member;

public:
A();
virtual ~A();

protected:
bool isMember();
};
#endif // _A_H_

//A.cpp
#include "A.h"

A::A(){_member=true;}

A::~A(){};

bool A::isMember()
{
return _member;
}

//B.h

#ifndef _B_H_
#define _B_H_
#include "A.h"

class B : public A
{
private:
A * _memberB;

public:
B( A *x);
~B();

};
#endif // _B_H_

//B.cpp

#include "B.h"
#include "A.h"

B::B(A * x)
{
if(x->isMember()) // call of the protected member of class A
this->_memberB=x;
}

B::~B()
{
//cout<<"B--"<<endl;
delete this->_memberB;
}

//main.cpp
#include "B.h"

int main()
{
A * a= new A();

B * b= new B(a);

return 0;
}

Answer

its a per-class not per-object basis

per-object:
you cant access parent class's protected member through child object from outside even though child can actually access parent's protected function:

Child c;
c.protectedFunction(); // wont work, because you are calling protectedFunction() outside the child object.

per-class
but you can access it through child class:

class Child : public Parent
{
    public: 
        void someFunction()
        {
            protectedParentFunction(); // it works! you are callign it from Child class
        }
}

to fix your problem, you should write a public function inside the Child class that calls the protected function from Parent class.

class Child : public Parent
{
    public: 
        void callerOfProtectedFunction()
        {
            protectedParentFunction();
        }
}
Child c;
c.callerOfProtectedFunction();