The Wayback Machine - https://web.archive.org/web/20241001003750/https://www.geeksforgeeks.org/cpp-inheritance-access/
Open In App

C++ Inheritance Access

Last Updated : 06 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites:

Before learning about Inheritance Access we need to know about access specifiers. There are three Access specifiers in C++. These are:

public – members are accessible from outside the class, and members can be accessed from anywhere.
private – members cannot be accessed (or viewed) from outside the class, i.e members are private to that class only.
protected – members cannot be accessed from outside the class, but, they can be accessed in inherited classes or derived classes.

Public, Protected, and Private inheritance in C++

public, protected, and private inheritance have the following features:

  • public inheritance makes public members of the base class public in the derived class, and the protected members of the base class remain protected in the derived class.
  • protected inheritance makes the public and protected members of the base class protected in the derived class.
  • private inheritance makes the public and protected members of the base class private in the derived class.

Accessibility Of Inheritance Access:

Inheritance access

Inheritance Access

1. C++ public Inheritance

In this example, public inheritance is demonstrated. Since private and protected members will not be directly accessed from main( ) so we have had to create functions name getPVT( ) to access the private variable and getProt( ) to access the protected variable from the inherited class.

Example:

C++
// C++ program to demonstrate the working of public
// inheritance
#include <iostream>
using namespace std;

class Base {
private:
    int pvt = 1;

protected:
    int prot = 2;

public:
    int pub = 3;

    // function to access private member
    int getPVT() { return pvt; }
};

class PublicDerived : public Base {
public:
    // function to access protected member from Base
    int getProt() { return prot; }
};

int main()
{
    PublicDerived object1;
    cout << "Private = " << object1.getPVT() << endl;
    cout << "Protected = " << object1.getProt() << endl;
    cout << "Public = " << object1.pub << endl;
    return 0;
}

Output
Private = 1
Protected = 2
Public = 3

2. C++ Protected Inheritance

We know that protected members can only be accessed from the Derived class. These members cannot be directly accessed from outside the class. So we cannot use getPVT() from ProtectedDerived. This is also why we need to create getPub() function in the Derived class in order to access the pub variable.

Example:

C++
// C++ program to demonstrate the working
// of protected inheritance
#include <iostream>
using namespace std;

class Base {
private:
    int pvt = 1;

protected:
    int prot = 2;

public:
    int pub = 3;

    // function to access private member
    int getPVT() { return pvt; }
};

class ProtectedDerived : protected Base {
public:
    // function to access protected member from Base
    int getProt() { return prot; }

    // function to access public member from Base
    int getPub() { return pub; }
      
      // function to get access to private members from Base
      int try_getPVT() {Base::getPVT(); }
};

int main()
{
    ProtectedDerived object1;
    cout << "Private = " << object1.try_getPVT() << endl;
    cout << "Protected = " << object1.getProt() << endl;
    cout << "Public = " << object1.getPub() << endl;
    return 0;
}

Output
Private = 1
Protected = 2
Public = 3

Note: There is still a way to access the Private members of base class. Since Base has a public member function that can access its private member variables, we can create a call to this member function (inherited as Protected member function in derived class) to access the Private inherited variable of Base class.

3. C++ Private Inheritance

We know that private members cannot be accessed from the Derived class. These members cannot be directly accessed from outside the class. So we cannot use getPVT() from PrivateDerived. So we need to create the getPub() function in PrivateDerived in order to access the pub variable.

Example:

C++
// C++ program to demonstrate the working
// of private inheritance
#include <iostream>
using namespace std;

class Base {
private:
    int pvt = 1;

protected:
    int prot = 2;

public:
    int pub = 3;

    // function to access private member
    int getPVT() { return pvt; }
};

class PrivateDerived : private Base {
public:
    // function to access protected member from Base
    int getProt() { return prot; }

    // function to access public member
    int getPub() { return pub; }
  
      // function to get access to private members from Base
      int try_getPVT() { Base::getPVT(); }
};

int main()
{
    PrivateDerived object1;
    cout << "Private = " << object1.try_getPVT() << endl;
    cout << "Protected = " << object1.getProt() << endl;
    cout << "Public = " << object1.getPub() << endl;
    return 0;
}

Output
Private = 1
Protected = 2
Public = 3


Previous Article
Next Article

Similar Reads

Difference between Single and Multiple Inheritance in C++
Single InheritanceSingle inheritance is one in which the derived class inherits the single base class either public, private, or protected access specifier. In single inheritance, the derived class uses the features or members of the single base class. These base class members can be accessed by a derived class or child class according to the acces
4 min read
Constructor in Multilevel Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multilevel Inheritance Derivation of a class from another derived class is called Multilevel Inheritance. Class A is the base class for the d
2 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The construct
2 min read
Inheritance Ambiguity in C++
Pre-requisites: Inheritance in C++, Multiple Inheritance in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes. If the derived class obje
6 min read
C++ Multilevel Inheritance
Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class inherits another class it is further inherited by another class. It is known as multi-level inheritance. For example, if we take Grandfather as a base class then Father is the derived class that has features of Grandfather and then Child is t
2 min read
C++ Hierarchical Inheritance
Inheritance is a feature of Object-Oriented-programming in which a derived class (child class) inherits the property (data member and member functions) of the Base class (parent class). For example, a child inherits the traits of their parents. In Hierarchical inheritance, more than one sub-class inherits the property of a single base class. There
4 min read
Hybrid Inheritance In C++
Before jumping into Hybrid Inheritance, let us first know what is inheritance. Inheritance is a fundamental OOP concept in C++ that allows a new class, also known as a subclass or derived class, to inherit properties and methods from an already-existing class, also known as a superclass or base class. C++ supports 5 types of inheritance: Single Inh
6 min read
Inheritance and Friendship in C++
Inheritance in C++: This is an OOPS concept. It allows creating classes that are derived from other classes so that they automatically include some of the functionality of its base class and some functionality of its own. (See this article for reference) Friendship in C++: Usually, private and protected members of a class cannot be accessed from ou
2 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 min read
Multiple Inheritance in C++
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B's constructor is called before A's constructor. A class can be derived from more than one base class. Eg: (i) A CHILD
5 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
Difference between Inheritance and Polymorphism
Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:Single inheritanceMulti-level inheritanceMultiple inheritancesHybrid inheritanceHierarchical inheritanceEx
5 min read
Does overloading work with Inheritance?
If we have a function in base class and another function with the same name in derived class, can the base class function be called from derived class object? This is an interesting question and as an experiment, predict the output of the following C++ program: [GFGTABS] C++ #include <iostream> using namespace std; class Base { public: int f(
5 min read
"Access is Denied error" in C++ Visual Studio and How to resolve it
Pre-requisite: How to Install Visual C++ on Windows In this article, we will discuss about access denied error in Visual Studio in C++. What is Access denied error in Visual Studio in C++? Access denied error in Visual Studio in C++ occurs when there is an attempt to access one of the installation files and due to some reason the access is denied t
3 min read
Different ways to access characters in a given String in C++
String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()substr()find()find_first_of()find_last_of() Let's start
4 min read
How to Access Elements in Set by Index in C++?
Sets are the containers that are available in the C++ Standard Template Library (STL). They are used to hold distinct elements in a predetermined sequence; fundamentally, it operates on the same principles as a binary search tree. In C++, elements can be added to or removed from sets, but they cannot be modified after being stored there since their
4 min read
How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?
Local Variable: The variable whose scope lies inside a function or a block in which they are declared. Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes. We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolutio
2 min read
What happens when more restrictive access is given to a derived class method in C++?
We have discussed a similar topic in Java here. Unlike Java, C++ allows to give more restrictive access to derived class methods. For example the following program compiles fine. C/C++ Code #include<iostream> using namespace std; class Base { public: virtual int fun(int i) { } }; class Derived: public Base { private: int fun(int x) { } }; int
2 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
Random Access Iterators in C++
After going through the template definition of various STL algorithms like std::nth_element, std::sort, you must have found their template definition consisting of objects of type Random-access Iterator. So what are they and why are they used?Random-access iterators are one of the five main types of iterators present in C++ Standard Library, others
6 min read
Access Modifiers in C++
Access modifiers are used to implement an important aspect of Object-Oriented Programming known as Data Hiding. Consider a real-life example: The Research and Analysis Wing (R&AW), having 10 core members, has come into possession of sensitive confidential information regarding national security. Now we can correlate these core members to data m
5 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
7 ways to Initialize Vector in C++
Vectors in C++, like Arrays, are one of the most extensively used entities and to initialize vectors in C++ is one of the most common issues that users face. One of the most commonly used methods for vector initialization is the Array style. But C++, along with this, provides several different methods to initialize a vector. In this post, we have l
6 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
vector erase() and clear() in C++
Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read