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();
}
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.