0

I put a class into another class. I put a reference of the highest level class into the lower level class (not sure if there's a nomenclature for this.. not child/parent..? subclass?). I am very surprised to see that I can call private functions from that sub class. Why is this possible?

Simple example: I am surprised Bar can call a private function from Foo

// Example program #include <iostream> #include <string> class Foo { public: class Bar { public: Bar(Foo &foo); void DoFoo(); private: Foo &foo; }; Foo(); private: void Do(); }; Foo::Foo(){} void Foo::Do(){ std::cout << "im doing foo"; } Foo::Bar::Bar(Foo &foo) :foo(foo) { }; void Foo::Bar::DoFoo(){ this->foo.Do(); } int main() { Foo foo; Foo::Bar bar(foo); bar.DoFoo(); } 
2

1 Answer 1

6

Actually access restrictions do not matter that much here, because (from cppreference, emphasize mine)...

All members of a class (bodies of member functions, initializers of member objects, and the entire nested class definitions) have access to all names the class can access.

In your example Bar is a nested class that can access all members of Foo (independent of whether they are declared private).

PS Note that this does not imply that also Foo has access to all members of Bar. For example Bar::foo is only visible within Bar because it is declared private.

Sign up to request clarification or add additional context in comments.

2 Comments

Worth noting that it doesn't work the other way around.
@sweenish well, being nested is also not commutative ;), but agreed I'll add a note

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.