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?

Recommended Answers

All 3 Replies

yes

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;
}

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.