Home > Backend Development > C++ > Can Inner Classes in C Access Their Parent Class\'s Private Variables?

Can Inner Classes in C Access Their Parent Class\'s Private Variables?

Mary-Kate Olsen
Release: 2024-11-29 08:04:10
Original
221 people have browsed it

Can Inner Classes in C   Access Their Parent Class's Private Variables?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template