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