jotaele jotaele - 12 days ago 8
C++ Question

Force a derived-class object to use its own function, not the base-class one

I have some doubts about subclasses in C++. I have this code:

class BaseClass() {
BaseClass();
void doSomething();
}

class SubClass : public BaseClass {
SubClass();
void doSomething();
}


When I declare a BaseClass object that could be a SubClass I do it calling the sub constructor...

BaseClass foo = SubClass();


Then I need foo to use the doSomething() method of the derived class, but when I do it this way...

foo.doSomething();


It uses the parent class method instead of the derived one. I tried this, but it doesn't work:

foo.SubClass::doSomething();


Is there any way to do it or I'm forced to declare the object with "SubClass" type to make it use its own function?

Answer

Use virtual and override:

class BaseClass() {
    BaseClass();
    virtual void doSomething();
}

class SubClass : public BaseClass {
    SubClass();
    void doSomething() override ;
}