C++: Inheritance

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

In a programming language like C++, inheritance is one of the core ideas of Object-Oriented program.

In inheritance, the derived class inherits the behaviors and attributes of its base class.

In our earlier examples, we have built a Rock class and a Country class.  In a way, pop or rock are just a genre in music.

We can understand pop or rock as a subclass of music.  So in an object-oriented program, we can build a base class called Music and another 2 derived classes called Pop or Rock.

Consider the following example.

#include <cstdlib>
#include <iostream>

using namespace std;

// Base class

class Music {

    void setSinger(string s) {
        singer = s;

    void setTitle(string t) {
        title = t;
    string singer;
    string title;

// Derived class

class Rock : public Music {

    int Display() {
        cout << singer << " singing " << title;      
        return 0;

class Pop : public Music {

    int Show() {
        cout << singer << " top 10 hit " << title;      
        return 0;

int main(void) {
    Rock rock;

    rock.setSinger("Rod Stewart");
    rock.setTitle("I Was Only Joking");

    cout << rock.Display() << endl;
    Pop pop;
    pop.setSinger("Taylor Swift");
    pop.setTitle("Blank Space");
    cout << pop.Show() << endl;

    return 0;

In line 19, we have declared 2 data members as protected.  This will allow them to be accessed by its derived class Rock or Pop.



Series Navigation<< C++: Applying public, private and protected keywords to the base class itself
C++: Inheritance and virtual method >>