问题
I can't reach a method of a sub-class' instance when several conditions are merged :
- There is in the super-class an attribute of type string.
- The instance have been created in a loop
- The instance is stored in a vector that takes super-class pointers
It's so look like this :
class Parent
{
public :
string name;
virtual void myMethod() = 0;
};
class Child : public Parent
{
public :
void myMethod();
};
void Child::myMethod()
{
cout << "I'm a child";
}
int main(void)
{
vector<Parent*> children;
for(unsigned int i = 0 ; i < 1; i++ )
{
Child c;
children.push_back(&c);
}
(*children[0]).myMethod();
}
In that case the code over with an error : "pure virtual method called terminate called without an active exception". I guess that it's trying to access to 'Parent::myMethod' that is virtual and so fail. To avoid that issue I can : - Remove the attribute 'name' of the super-class - Change the type of that attribute (to int for exemple) - Append the elements to the vector from outside of the for loop.
I just can't figure what is going on in that specific case...
回答1:
There is only one "condition" that matters here: the pointers you push in the vector point to garbage when Child c;
goes out of scope:
{
Child c; // this object lives only in this scope !!
children.push_back(&c); // <-- &c is fine here
} // <-- already here it is not !
(*children[0]).myMethod(); // ***BOOM***
Maybe you got the impression that it is a specific combination of conditions to get the error, but thats just because dereferencing an invalid pointer is undefined behaviour, so sometimes it may look like it worked when actually it is never correct.
来源:https://stackoverflow.com/questions/45959875/method-of-super-class-called-when-super-has-a-str-attr-instance-of-sub-is-crea