C++: Applying the 3 classes to the base class

This entry is part 51 of 61 in the series C++

Here is the example to illustrate the 3 classes that have been applied to the base class.

The explanations are in the comments in the code block.

#include <iostream>

using namespace std;

class Base {
public:
    int x;
protected:
    int y;
private:
    int z;
};

class D1 : public Base {
    // x is public
    // y is protected
    // z is not accessible from D1
    
public:
    
    void printOut()
    {
        int x = 1;
        cout << x << endl;
        
        int y = 1;
        cout << y << endl;
    }
    
};

class D2 : protected Base {
    // x is now inherited as protected here
    // y is now inherited as protected here
    // z is not accessible from D2
    
    
public:
    
    void printOut()
    {
        int x = 2;
        cout << x << endl;
        
        int y = 2;
        cout << y << endl;
    }
    
};

class D3 : private Base {
    // x is inherited as private and so accessible by D3 class itself
    // y is inherited as private and so accessible by D3 class itself
    // z is not accessible from D3
    
    public:
    
    void printOut()
    {
        int x = 3;
        cout << x << endl;
        
        int y = 3;
        cout << y << endl;
    }
    
};

int main() {
  
    D1 d1;
    d1.printOut();
    
    D2 d2;
    d2.printOut();
    
    D3 d3;
    d3.printOut();
    
}

3classes

Series Navigation<< C++: Constructor in C++ 11
C++: Assessing class members from main >>
Posted in