Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access protected members in a derived class?

From http://www.parashift.com/c++-faq-lite/basics-of-inheritance.html#faq-19.5

A member (either data member or member function) declared in a protected section of a class can only be accessed by member functions and friends of that class, and by member functions and friends of derived classes

So, what is the way to access the protected function fun in the derived class?

#include <iostream>
using namespace std;

class X
{
    private:
        int var;
    protected:
        void fun () 
        {
            var = 10;
            cout << "\nFrom X" << var; 
        }
};

class Y : public X
{
    private:
        int var;
    public:
        void fun () 
        {
            var = 20;
            cout << "\nFrom Y" << var;
        }

        void call ()
        {
            fun ();

            X objX;
            objX.fun ();
        }
};

This results in:

anisha@linux-dopx:~/> g++ type.cpp
type.cpp: In member function ‘void Y::call()’:
type.cpp:9:8: error: ‘void X::fun()’ is protected
type.cpp:32:14: error: within this context

I saw this: Accessing protected members in a derived class

Given:

You can only access protected members in instances of your type (or derived from your type). You cannot access protected members of an instance of a parent or cousin type.

In your case, the Derived class can only access the b member of a Derived instance, not of a different Base instance.

Changing the constructor to take a Derived instance will also solve the problem.

How can this be accomplished without changing the constructor declaration?

like image 544
Aquarius_Girl Avatar asked Dec 05 '22 18:12

Aquarius_Girl


1 Answers

One solution is to add friend class Y to X.

like image 137
Anycorn Avatar answered Dec 07 '22 09:12

Anycorn