Novice_Developer
Novice_Developer

Reputation: 1492

Derived class cannot access the protected member of the base class

Consider the following example

class base
{
protected :
    int x = 5;
    int(base::*g);
};
class derived :public base
{
    void declare_value();
    derived();
};
void derived:: declare_value()
{
    g = &base::x;
}
derived::derived()
    :base()
{}

As per knowledge only friends and derived classes of the base class can access the protected members of the base class but in the above example I get the following error "Error C2248 'base::x': cannot access protected member declared in class " but when I add the following line

friend class derived;

declaring it as friend , I can access the members of the base class , did I do some basic mistake in the declaring the derived class ?

Upvotes: 12

Views: 9013

Answers (2)

nvoigt
nvoigt

Reputation: 77295

My compiler actually said I needed to add a non-default constructor to base because the field is not initialized.

After I added

base() : g(&base::x) {}

it did compile without problems.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172894

The derived class could access the protected members of base class only through the context of the derived class. On the other word, the derived class can't access protected members through the base class.

When a pointer to a protected member is formed, it must use a derived class in its declaration:

struct Base {
 protected:
    int i;
};

struct Derived : Base {
    void f()
    {
//      int Base::* ptr = &Base::i;    // error: must name using Derived
        int Base::* ptr = &Derived::i; // okay
    }
};

You can change

g = &base::x;

to

g = &derived::x;

Upvotes: 13

Related Questions