timakro
timakro

Reputation: 1841

Call method of subclass from superclass

Take a look at this sample, there are 3 classes inheriting from bell. They overwrite different methods of bell.

#include <iostream>
using namespace std;

class bell {
public:
    void noise() {
        cout << "dung" << endl;
    }
    void ring() {
        noise();
        noise();
    }
};

class short_bell : public bell {
public:
    void ring() {
        noise();
    }
};

class annoying_bell : public bell {
public:
    void noise() {
        cout << "ding" << endl;
    }
    void ring() {
        noise();
        noise();
        noise();
        noise();
        noise();
    }
};

class slow_bell : public bell {
public:
    void noise() {
        cout << "dooong" << endl;
    }
};

int main()
{
    cout << "church bell" << endl;
    bell church_bell;
    church_bell.ring();

    cout << "bicycle bell" << endl;
    short_bell bicycle_bell;
    bicycle_bell.ring();

    cout << "doorbell" << endl;
    annoying_bell doorbell;
    doorbell.ring();

    cout << "school bell" << endl;
    slow_bell school_bell;
    school_bell.ring();

    return 0;
}

Output:

church bell
dung
dung
bicycle bell
dung
doorbell
ding
ding
ding
ding
ding
school bell
dung
dung

Everything works as I expected it but the school_bell. slow_bell inherits from bell and overwrites the noise method. When the ring method of slow_bell is called it falls back to its parent bell but when the ring method of bell calls noise it is called the noise method of bell, instead I want it to call the noise method of slow_bell.

What is the best way to achieve this?

Upvotes: 0

Views: 71

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36483

Make them virtual and override the methods :

Bell:

class bell {
public:
    virtual void noise() {
        cout << "dung" << endl;
    }
    void ring() {
        noise();
        noise();
    }
};

slow_bell:

class slow_bell : public bell {
public:
    void noise() override {
        cout << "dooong" << endl;
    }
};

Upvotes: 2

Related Questions