Inner Classes Accessing Private Variables in C
In C , inner classes have the unique ability to access private members of the enclosing class. Consider the following example:
class Outer { class Inner { public: Inner() {} void func(); }; private: static const char* const MYCONST; int var; };
In this example, the Inner class is defined within the Outer class. According to traditional scope rules, the var member variable of Outer should not be accessible to Inner. However, in C , inner classes are inherently friends of their enclosing class.
As a result, objects of type Outer::Inner can access the private member variables of Outer. However, it's important to note that this access is only granted within the scope of the inner class.
To further illustrate this concept, let's modify the func() method of Inner class as follows:
void Outer::Inner::func() { var = 1; }
Now, if we try to compile this code, we will encounter an error message indicating that 'class Outer::Inner' has no member named 'var'. This is because while inner classes have access to private members, they do not inherit a member relationship with the enclosing class.
To establish a proper member relationship within the inner class, we need to manually create a reference to the enclosing class, as shown in the following example:
class Outer { class Inner { public: Inner(Outer& x): parent(x) {} void func() { std::cout << parent.var << std::endl; } private: Outer& parent; }; public: Outer() : i(*this), var(4) {} void func() { i.func(); } private: Inner i; int var; }; int main() { Outer o; o.func(); }
In this example, the Inner class constructor takes a reference to the Outer class as an argument. This allows objects of type Outer::Inner to access the private members of Outer through the parent reference.
The above is the detailed content of How Can Inner Classes in C Access Private Members of Their Enclosing Class?. For more information, please follow other related articles on the PHP Chinese website!