Skip to main content
The 2024 Developer Survey results are live! See the results
edited tags
Link
songyuanyao
  • 171.9k
  • 16
  • 321
  • 424
Source Link
Novice_Developer
  • 1.5k
  • 2
  • 20
  • 35

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 ?