Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 659
Novice_Developer Avatar asked Aug 13 '18 14:08

Novice_Developer


People also ask

Can derived class access protected members?

Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

Does base class have access to derived class?

In all cases, private members of the base class remain private. Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.

Can we access protected member derived class in Java?

Protected Access Modifier - Protected Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces.

Can a object of a derived class Cannot access private members of base class?

Derived class can not access the private members of it's base class. No type of inheritance allows access to private members. However if you use friend declaration you can do that. Save this answer.


1 Answers

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;
like image 74
songyuanyao Avatar answered Oct 05 '22 03:10

songyuanyao