Access Specifier Example in C++


This code defines two classes Base and Derived where Derived is derived from Base class publicly. The Base class has private, protected, and public data members and a member function funBase() which initializes and displays the sum of a, b, and c.

The Derived class does not have any data members or member functions but inherits the Base class's public and protected data members. In the main function, an object of Base class is created named b. The funBase() function of Base class is called using the b object which initializes and displays the sum of a, b, and c.

The code tries to access the private data member a and protected data member b of the Base class outside the class, which is not allowed. The c data member of Base class can be accessed outside the class.

Source Code

#include<iostream>
using namespace std;
class Base
{
private:
    int a;
protected:
    int b;
public:
    int c;
    void funBase()
    {
        a=10;
        b=5;
        c=15;
        cout<<"Result :"<<a+b+c;
    }
};
class Derived:public Base
{
public:
    void funDerived()
    {
       // a=10;
        b=5;
        c=15;
    }
};
int main()
{
    Base b;
    b.funBase();
 
//    b.a=10; Private
   // b.b=5;  Protectd
    b.c=20;
}
 
To download raw file Click Here

Output

Result :30

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples