I'm new to these concepts but a derived class cannot access private members of the base class because they are simply not accessible externally. But what if I define the derived class in a friend function to the base class. will the private members of the base class be successfully derived and if yes, will they be as public or private, or depend on the type of derivation?

Thanks,
Abhinav

does C++ even have method-local inner classes?

This is compiled and run with VC++ 2005 Express with no errors.

class A;
class Base
{
private:
	int m_x;
public:
	friend A;
	Base() {m_x = 1;}
};

class A : public Base
{
public:
	A() {m_x = 2;}
	int getX() {return m_x;}
};

int main()
{
	A a;
	cout << a.getX() << endl;
	return 0;
}

But what if I define the derived class in a friend function to the base class. will the private members of the base class be successfully derived and if yes, will they be as public or private, or depend on the type of derivation?

Yes, they'll be successfully derived. That's going to happen no matter where the derived class is defined. It's a basic rule of inheritance. ;) The funny thing is that the derived class sort of inherits the access rights of the friend function and the private members of the base class are accessible to both the friend function and the derived class thanks to the "is a" rule.

I'm not sure that's right, but it compiles on the strictest modes of the most conforming compiler I know of. :)

Thanks, this is a great first experience here on Daniweb. The replies were very informative.


The funny thing is that the derived class sort of inherits the access rights of the friend function and the private members of the base class are accessible to both the friend function and the derived class thanks to the "is a" rule.

So, you mean to say that the friend function is also now a friend function to the derive class. That practically means that within that function, any private members of the derived class can be accessed, right?

So, you mean to say that the friend function is also now a friend function to the derive class. That practically means that within that function, any private members of the derived class can be accessed, right?

That's the impression that I get. :) I'm not sure you can rely on it because the rules for friends shouldn't do that. A friend of mine is not necessarily a friend of my children. ;) But I don't claim to understand most of C++, and there could be some tricky rules hidden in there that allow your situation. A good place to ask the super gurus is comp.lang.c++.

Ok, thanks. I'll check out the group you mentioned too.

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.