C++: Assessing private members of the base class

In the previous example, we have used only public members for the base class.

However, there are 3 types of data members for a class, public, private and protected.

If a data member is declared as private, this data member could only be accessible by its member functions.

Consider the following example.

#include <cstdlib>
#include <iostream>

using namespace std;

// Base class

class Music {
    
private:
    string singer;
    string title;

public:

    string printOut() {
        
        this->singer = "Katy Perry";
        
        return this->singer;
    }
};

// Derived class

class Rock : public Music {

public:
    
    string album;
    
};

int main(void) {

    Rock rock;

    cout << rock.printOut();
    
    return 0;
}

Rock is a derived class of Music.  For it to access the private members of the base class, in this case, the singer variable, we have another public method called printOut.

It is through this printOut method that we are able to access the private member singer.

private

Series Navigation<< C++: Members of a subclass
C++: Constructor in C++ 11 >>