C++: Pure virtual function turns a class into abstract class

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

In C++, once you have a pure function in a class, you turn that class into an abstract class.  There is no need to define a class as abstract.

This is unlike other programming languages such as C# shown in this post here.

Abstract class in OOP is meant for us to define a general or generic class so that we can derive a more specific class from it.

There is no actual method implementation in the class.  In our example here, Music class has a pure virtual function and so it is now an abstract class.

The actual implementation of the display method is done by the derived class Rock or Country.

#include <iostream>

using namespace std;

class Music {
public:
    virtual void display() = 0;  //Pure virtual function
    
};

class Rock : public Music {
public:
    void display(); // OVERRIDE!
    
};

class Country : public Music {
public:
    void display(); // OVERRIDE!

};

void Rock::display() {

    cout << "Janie Got A Gun By Aerosmith";

}

void Country::display() {
    cout << "Strawberry Wine by Deana Carter";
}

int main(int argc, char** argv) {

    Rock rock;
    Country country;

    rock.display();
    cout << endl;
    country.display();

    return 0;
    
}

abstract

 

Series Navigation<< C++: Pure virtual function
C++: Friend functions >>

Leave a comment

Leave a Reply