C++: Inheritance and virtual method

In an Object-Oriented program, a Virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same name.

This concept is an important part of the polymorphism or specialization portion of object-oriented programming (OOP).

#include <iostream>
#include <string.h>

using namespace std;

class Music {
public:

    Music(int iAge, char* sName) {
        this->iAge = iAge;
        strcpy(this->sName, sName);
    }

    virtual char* WhoAmI() {
        return "I am a musician";
    }
private:
    int iAge;
    char sName[32];
};

class Rock : public Music {
public:

    Rock(int iAge, char* sName, char* latestAlbum)
    : Music(iAge, sName) {
        strcpy(this->latest, latestAlbum);
    }

    virtual char* WhoAmI() {
        return "I am a rock star";
    }
private:
    char latest[32];
};

class Country : public Music {
public:

    Country(int iAge, char* sName, char* liveConcert)
    : Music(iAge, sName) {
        strcpy(this->live, liveConcert);
    }

    virtual char* WhoAmI() {
        return "I am a country singer";
    }
private:
    char live[32];
};

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

    Music musician(26, "John");
    cout << musician.WhoAmI() << endl;

    Rock rocker(35, "Mary", "In A Band");
    cout << rocker.WhoAmI() << endl;

    Country countrySinger(22, "Sandra", "Live performance");
    cout << countrySinger.WhoAmI() << endl;

    return 0;
}

 

What is important for us to know is that when you declare an object, its constructor is being called.

When you declare an object of a derived class, the constructor from the base class is called first, and the constructor from the derived class is called later.

Rock(int iAge, char* sName, char* latestAlbum)
    : Music(iAge, sName) {
        strcpy(this->latest, latestAlbum);
    }

virtual

Series Navigation<< C++: Inheritance
C++: Static variable >>