Home > front end >  c how to overwrite method in subclass
c how to overwrite method in subclass

Time:06-07

I have some code I'm trying to get to work, I'm open to other suggestions on how to do this. Basically, I have some base class that I want a bunch of subclasses to inherit. I then have a function that needs to call the subclass version of this method.

#include <iostream>

using namespace std;

//my base class
class BaseClass {
    public:
    void myMethod(){
        std::cout  << "Base class?" << std::endl;
    }
};

/my subclass
class SubClass1: public BaseClass{
    public:

    void myMethod(){
        std::cout << "Subclass?" << std::endl;
    }
};

//method that I want to call SubClass.myMethod(). I cannot declare this as
//SubClass1 because there will be multiple of these.

void call_method(BaseClass object){
    return object.myMethod();
}


int main()
{
    BaseClass bc;
    SubClass1 sb1;

    //works how I expect it to
    sb1.myMethod();
    //I want this to also print "Subclass?"
    //but it prints "Base class?".
    call_method(sb1);



    return 0;
}

Thanks for your help

CodePudding user response:

You need to declare the member function in the base class as virtual. For example

virtual void myMethod() const {
    std::cout  << "Base class?" << std::endl;
}

And in the derived class to override it

void myMethod() const override {
    std::cout << "Subclass?" << std::endl;
}

And the function call_method must have a parameter that represents a reference to base class object

void call_method( const BaseClass &object){
    object.myMethod();
}
  • Related