• Advertisement
Sign in to follow this  

C++ inheritance/constructor overiding

This topic is 4428 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

why does it In constructor `StaticSprite::StaticSprite(double, double)': no matching function for call to `WorldSprite::WorldSprite()' (in dev C++)
#define GameUnit double

class WorldSprite{
  public:

//if i delete this its ok, dosent like me overriding
//constructor or something
WorldSprite(GameUnit X,GameUnit Y){x=X;y=Y;} 

GameUnit x,y;


};

class StaticSprite: public WorldSprite{
  public:
StaticSprite(GameUnit X,GameUnit Y){x=X;y=Y;} 

};

class CharaSprite: public WorldSprite{
  public:
CharaSprite(GameUnit X,GameUnit Y){x=X;y=Y;} 

};

Share this post


Link to post
Share on other sites
Advertisement
Try doing


class StaticSprite: public WorldSprite{
public:
StaticSprite(GameUnit X,GameUnit Y):WorldSprite(X,Y) {}

};




and do the same with the other derived class

Share this post


Link to post
Share on other sites
thanks
that worked, but what does it do/mean exactly

Share this post


Link to post
Share on other sites
When you instantiate a derived class (e.g. StaticSprite), the constructor will call the constructors of the parent classes automatically. Unless you specify otherwise, the parent constructors with zero parameters will be called (e.g. StaticSprite(double,double) will try to call WorldSprite() ).

When you add WorldSprite(X,Y) to the initializer list of StaticSprite(double, double), you are telling the compiler to call a different constructor for WorldSprite, so it does not require that WorldSprite() be defined. It will instead require that WorldSprite(double, double) is defined.

For any class, the compiler will create a default constructor that takes zero parameters if you do not define your own constructor. If you DO define a constructor, the compiler will NOT create that default constructor.

This is why the behavior changes when you delete
WorldSprite(GameUnit X,GameUnit Y){x=X;y=Y;}
from your WorldSprite definition. When StaticSprite(double, double) is called, the compiler tries to call WorldSprite(). With the above line, there is no WorldSprite(), but when you delete it, there is one (because the compiler creates one).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement