C++: Pure virtual function

In the previous post, the Music class has a method called display.  This base class has its own implemention of display() method but it is an implementation that did nothing.

We can declare the Music class to have no implementation at all.  This is done by using pure virtual function, with the syntax.

virtual void display() = 0;

A class with at least one pure virtual function is an abstract class. Such a class cannot be instantiated, meaning that you cannot use it to declare objects, at least not directly.

We will talk about abstract class in the later post.

#include <iostream>

using namespace std;

class Music {
public:
    virtual void display() = 0;

};

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;

    Music *ptr_music;

    ptr_music = &rock;
    ptr_music->display(); // Call Rock::display()
    cout << endl;
    ptr_music = &country;
    ptr_music->display(); // Call Country::sound()

    return 0;

}

pure

Series Navigation<< C++: Pointer to access methods in derived classes
C++: Pure virtual function turns a class into abstract class >>