I’m sure this is just some stupid syntax error I’m making, but when my class CNeck derived from CLimb calls its default constructor, CNeck() everything works as expected. When it calls a different constructor CNeck(*parent) it seems to call about half of the specified base constructor, then gives uses the compiler default constructor or something weird.
main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
CNeck neck01;
CLimb *ptr;
ptr = &neck01;
CNeck neck02(ptr);
return 0;
}
limb.h (parent class)
class CLimb
{
public:
CLimb(void);
CLimb(CLimb *_parent);
~CLimb(void);
float cut;
float bone;
float resistance;
//attributes
bool isBurned;
bool isBleeding;
bool isOnFire;
bool isNeedFirstaid;
CLimb *parent;
};
limb.cpp (parent class)
#include "limb.h"
CLimb::CLimb(void) :
cut(10),
bone(10),
resistance(10),
//attributes
isBurned(0),
isBleeding(0),
isOnFire(0),
isNeedFirstaid(0)
{
parent = NULL;
}
CLimb::CLimb(CLimb *_parent) :
cut(10),
bone(10),
resistance(10),
//attributes
isBurned(0),
isBleeding(0),
isOnFire(0),
isNeedFirstaid(0)
{
parent = _parent;
}
CLimb::~CLimb(void)
{
}
neck.h (child class)
#include "limb.h"
class CNeck :
public CLimb
{
public:
CNeck(void);
CNeck(CLimb *_parent);
~CNeck(void);
};
neck.cpp (child class)
#include "Neck.h"
CNeck::CNeck(void)
{
}
CNeck::CNeck(CLimb *_parent) : CLimb(*_parent)
{
}
CNeck::~CNeck(void)
{
}
As you can see, the child class doesn’t do anything other than call the parent’s constructor, yet when I step through the program I get the following results:
CNeck neck01;: normal
CNeck neck02(ptr);: values cut, bone, resistance, and isBurned all have proper values, but isBleeding, isOnFire, and isNeedFirstaid all equal 1 instead of zero. The body of CNeck::CNeck(*parent) is still executed.
When I was testing and called CLimb limb(ptr); instead of CNeck neck02(ptr); all the values were assigned the correct values.
Your constructor is marked
CLimb(CLimb *_parent);meaning it takes a pointer to a CLimb but in theCNeckconstructor,you’re dereferencing the pointer, which calls
CLimb(CLimb&)which is the copy constructor. Turn*_parentinto_parentto resolve this problem. Plus you might want to define a copy constructor as well.In other news, don’t do this:
Do this:
To avoid wasting cycles.
And you also don’t need
voidin the parameter list for functions which take no parameters (that’s the way C does it, not C++). So for example:Should be
I know it’s not related to your question, but it’s good style.