0

I have a std::vector<BaseClass> which I iterate over to call a update() method which makes use of another class method (isTrue() in the example below). This other method is overwritten by child classes to specify what exactly to do. But it seems that always the method of BaseClass is used. Is there any way to make use of the overwritten methods in this case?

/* baseclass.hpp */
#include <iostream>

class BaseClass {
    public:
        const int type;
        BaseClass(int t);

        void update();
        virtual bool isTrue();
};

/* baseclass.cpp */
BaseClass::BaseClass(int t) : type(t) {
}

void BaseClass::update() {
    if (isTrue())
        std::cout << "BaseClass" << std::endl;
    else
        std::cout << "Something else" << std::endl;
}

bool BaseClass::isTrue() {
    std::cout << "isTrue() BaseClass, type " << type << std::endl;
    return true;
}

/* childclass.hpp */
class ChildClass : public BaseClass {
    public:
        ChildClass();
        bool isTrue() override;
};

/* childclass.cpp */
ChildClass::ChildClass() : BaseClass(1) {
}

bool ChildClass::isTrue() {
    std::cout << "isTrue() ChildClass" << std::endl;
    return false;
}

/* somewhereelse.cpp */
#include <vector>
int main() {
    std::vector<BaseClass> list;

    list.push_back(ChildClass());
    list[0].update();
}

The output (like most of you expected I guess) is

isTrue() BaseClass, type 1
BaseClass

Is there a possibility that ChildClass::isTrue() is invoked in such a situation? or is there a way around it? (The filenames are just to indicate that I use different files in the real scenario, but this doesn't seem to make any difference)

I appreciate any help

  • 1
    It should be a vector of unique pointers to the base class. If you know how to write polymorphic code, adding it to a vector doesn’t change anything. – sweenish Jan 02 '23 at 00:27
  • 2
    A `std::vector` contains `BaseClass`s and *never* `ChildClass`s. The reason the `BaseClass` method is called is because you *are* calling the method on a `BaseClass` object. (`list.push_back(ChildClass())` is actually adding a `BaseClass` object to `list`.) You must store pointers in the vector, as in [this old question](https://stackoverflow.com/questions/8777724/store-derived-class-objects-in-base-class-variables). Note that nowadays you should be storing `unique_ptr`s or `shared_ptr`s instead of raw pointers. – HTNW Jan 02 '23 at 00:28

0 Answers0