Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

c++ - method of super-class called WHEN super has a str attr + instance of sub is created in a loop + instance is stored in a vector as a pointers of super

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...