Home >Backend Development >C++ >How Do Access Specifiers (private, protected, public) Affect Member Accessibility in Inheritance?

How Do Access Specifiers (private, protected, public) Affect Member Accessibility in Inheritance?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 18:11:11125browse

How Do Access Specifiers (private, protected, public) Affect Member Accessibility in Inheritance?

Understanding Access Specifiers in Inheritance

Inheritance allows classes to inherit members and functionality from parent classes, but the accessibility of these inherited members depends on the access specifiers used. The access specifiers private, protected, and public control how members are accessed in inherited classes.

Private Inheritance

  • Private members of a base class remain private in the derived class.
  • Protected and public members of the base class become private in the derived class.
  • Derived classes lose the ability to access the private members of the base class.

Example:

class Base {
private:
    int private_member;
};

class Derived : private Base {
public:
    void accessPrivate() {
        // Error: Cannot access 'private_member' because it's private in 'Base'
    }
};

Protected Inheritance

  • Public members of a base class become protected in the derived class.
  • Protected members of the base class remain protected in the derived class.
  • Derived classes can access the protected members of the base class both directly and through pointers to base class objects.

Example:

class Base {
protected:
    int protected_member;
};

class Derived : protected Base {
public:
    void accessProtected() {
        protected_member = 100; // Allowed
    }
};

Public Inheritance

  • Public and protected members of a base class become public in the derived class.
  • Private members of the base class remain private in the derived class.
  • Derived classes can access all public members of the base class, directly or through pointers.

Example:

class Base {
public:
    int public_member;
};

class Derived : public Base {
public:
    void accessPublic() {
        public_member = 200; // Allowed
    }
};

Considerations:

  • Access specifiers apply per class, not per object.
  • Derived classes can only access members of their own base class objects.
  • Friends can access all members of a class regardless of access specifiers.

The above is the detailed content of How Do Access Specifiers (private, protected, public) Affect Member Accessibility in Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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