I am running into an issue where an overloaded function is not called, and the base function is called instead. I suspect this is related to how things are split between the project files.
In files obj1.h/obj1.cpp I have something like this
class obj1{
public:
void print();
};
void obj1::print(){
cout << "obj1::print()";
}
In files obj2.h/obj2.cpp I have something like this:
#include "obj1.h"
class obj2 : public obj1{
public:
void print();
};
void obj2::print(){
cout << "obj2::print()";
}
In separate files, I do something like this:
#include "obj1.h"
class obj3{
public:
vector<obj1*> objlist;
void printobjs();
void addobj(obj1* o);
};
void obj3::printobjs(){
vector<obj1*>::iterator it;
for (it=objList.begin(); it < objList.end(); it++)
(*it)->print();
void obj3::addobj(obj1* o){
objlist.push_back(o);
}
Then in a different file:
#include "obj2.h"
obj3 o3;
main(){
obj2* newobj2;
newobj2 = new obj2();
o3.addobj(newobj2);
o3.printobjs();
My issue is that printobjs() results in the obj1.print() being called. (I have searched around a bit, and read a few dozen posts with overloading issues, but did not see a similar issue)
Can someone point me in the right direction on this? Thanks!
print
is not a virtual function, so you are just relying on static dispatch. This will select the function to call based on the static type of the object, which is obj1
in this case.
You should make print
virtual:
class obj1{
public:
virtual void print();
};
Then if you use C++11 you can mark obj2::print
as override
for safety's sake:
class obj2 : public obj1{
public:
void print() override;
};
Also note that you never allocate any memory for newobj2
.
You should declare print()
as virtual to calling obj2::print() for obj2 objects.
virtual void print();
I am not entirely sure, it is log time since i did c++, but as I remember You should have the vectors contents be classes with pure virtual functions.
That should force it to look up the right method.
There is a stack overflow answer here, which is slightly related:
来源:https://stackoverflow.com/questions/33936329/c-overridden-function-not-called