C++: Assessing private members of the base class

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

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 {
    string singer;
    string title;


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

// Derived class

class Rock : public Music {

    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.


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

Leave a comment

Leave a Reply