Access Specifiers in Inheritance

Lesson Introduction

Welcome to our lesson on "Access Specifiers in Inheritance" in C++! Access specifiers (public, protected, and private) are key in object-oriented programming as they help control access to class members. This lesson will focus on understanding how these access specifiers work in inheritance.

By the end of this lesson, you'll know how access specifiers affect the accessibility of inherited class members.

Access Specifiers Overview

In C++, access specifiers set the accessibility of class members (attributes and methods). The primary access specifiers are:

  • public: Members are accessible from outside the class.
  • protected: Members are accessible within the class and by derived class instances.
  • private: Members are accessible only within the class declaring them.

These controls help ensure data encapsulation and security by preventing unauthorized access. We have already seen public and private specifiers in the previous course. Let's discuss the protected in deeper details.

The Protected Specifier in Detail

The protected specifier in C++ allows members to be accessible within the same class, as well as any derived classes. However, these members are not accessible from code that is outside the class hierarchy.

Let's consider the following example to understand the protected specifier more clearly:

#include <iostream>

class Parent {
    protected:
        int protectedVar;
    public:
        Parent() : protectedVar(0) {}
        void setProtectedVar(int val) {
            protectedVar = val;
        }
};

class Child : public Parent {
    public:
        void display() {
            std::cout << "protectedVar: " << protectedVar << std::endl;  // OK: Accessible within derived class
        }
};

int main() {
    Child obj;
    // obj.protectedVar = 10;  // Error: protectedVar is not accessible outside the class hierarchy
    obj.setProtectedVar(10);  // OK: Access through public member function of the base class
    obj.display();            // Output: protectedVar: 10
    return 0;
}

In this example:

  • protectedVar is declared as protected in the Parent class.
  • The Child class, which is derived from Parent, can access protectedVar directly within its member functions.
  • From main(), direct access to protectedVar is not allowed, ensuring that it remains encapsulated within the class hierarchy.

Advantages of Using Protected:

  1. Encapsulation with Controlled Exposure: While private members totally encapsulate data, protected members allow derived classes to reuse and extend functionality.
  2. Inheritance Flexibility: Derived classes can build upon the base class without exposing sensitive data to the outside world.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal