0

If I do a public inheritance and the member data in the base class I'm deriving from is protected, is the only way to access the data in the base class via member/friend functions of the derived class?

3
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by John A
0

ok cuz I thought that I could just directly access protected member data in the base class through an instance of the derived class (the uncommented part doesn't work). I'm not sure why that is though so I'll just assume its a rule.

#include <iostream>

using std::cout;

class A
{
public:
	A() : a(10) {}
protected:
	int a;
};

class B : public A
{
public:
	int getInt() { return a; }
};

int main(void)
{
	A instanceA;
	B instanceB;

//	cout << instanceB.a;
	cout << instanceB.getInt() << '\n';

	return 0;
}
0

>I'm not sure why that is though so I'll just assume its a rule.
It's a rule. Protected members are, obviously, protected from the public, and should only be accessible from within the class. Using a hack to get around the limitation destroys the whole purpose of using non-public members.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.