Inner Class Access to Private Variables
In C , inner classes are nested within other classes and have special access privileges. The question arises: can inner classes access private variables of their parent class?
The answer is yes. Inner classes are essentially friends of the class they are defined within. This means that an object of an inner class can directly access the private members of an object of its parent class.
However, unlike in Java, there is no implicit parent-child relationship between an inner class object and an object of its parent class. To establish this relationship, the parent class object must be explicitly passed to the constructor of the inner class.
Here's a code example demonstrating inner class access to private variables:
#include <iostream> class Outer { private: int var = 4; static const char* const MYCONST = "myconst"; public: class Inner { public: Inner(Outer& parent) : parent(parent) {} void func() { std::cout << parent.var << std::endl; } private: Outer& parent; }; }; int main() { Outer outer; Outer::Inner inner(outer); inner.func(); return 0; }
In this example, the inner class Inner has a constructor that takes a reference to the parent Outer object as an argument. This establishes the parent-child relationship, allowing the inner class to access the private variable var of the Outer object.
When Inner::func() is called, it prints the value of the private variable var, demonstrating that inner classes can indeed access private variables of their parent class.
The above is the detailed content of Can Inner Classes in C Access Their Parent Class\'s Private Variables?. For more information, please follow other related articles on the PHP Chinese website!