C++: Pointer to access methods in derived classes

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

Since we have gone through one example on a pointer, we make some modifications to our earlier example to use pointer.

We have declared only one ptr_music and with the right referencing, we can use the pointer to access the methods in the derived classes.

When you declare a method as virtual, you are basically setting it up to be overridden by derived classes.

#include <iostream>

using namespace std;

class Music {
public:
    virtual void display();  //setting it up to be overridden
    
};

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

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

};

void Music::display() {
}

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) {

    Music music;
    
    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::display()

    return 0;
    
}

pointer2

Series Navigation<< C++: Pointers in class
C++: Pure virtual function >>

Leave a comment

Leave a Reply