Please see the example code below:
class A { private: class B { public: foobar(); }; public: foo(); bar(); };
Within class A & B implementation:
A::foo() { //do something } A::bar() { //some code foo(); //more code } A::B::foobar() { //some code foo(); //<<compiler doesn't like this }
The compiler flags the call to foo() within the method foobar(). Earlier, I had foo() as private member function of class A but changed to public assuming that B's function can't see it. Of course, it didn't help. I am trying to re-use the functionality provided by A's method. Why doesn't the compiler allow this function call? As I see it, they are part of same enclosing class (A). I thought the accessibility issue for nested class meebers for enclosing class in C++ standards was resolved.
How can I achieve what I am trying to do without re-writing the same method (foo()) for B, which keeping B nested within A?
I am using VC++ compiler ver-9 (Visual Studio 2008). Thank you for your help.
Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
Explanation: The non-static nested class can access all the members of the enclosing class. All the data members and member functions can be accessed from the nested class.
This is given as follows. class A { public: class B { private: int num; public: void getdata(int n) { num = n; } void putdata() { cout<<"The number is "<<num; } }; }; In the function main(), an object of the class A and class B is defined. Then the functions getdata() and putdata() are called using the variable obj.
Nested Classes in C++ A nested class is a class which is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.
foo()
is a non-static member function of A
and you are trying to call it without an instance.
The nested class B
is a seperate class that only has some access privileges and doesn't have any special knowledge about existing instances of A
.
If B
needs access to an A
you have to give it a reference to it, e.g.:
class A { class B { A& parent_; public: B(A& parent) : parent_(parent) {} void foobar() { parent_.foo(); } }; B b_; public: A() : b_(*this) {} };
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