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?
One solution is to add friend class Y
to X.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With