Derived Class not Calling Entire Base Constructor
I'm sure this is just some stupid syntax error I'm making, but when my class 开发者_JS百科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.CNeck::CNeck(CLimb *_parent) : CLimb(*_parent)
should be
CNeck::CNeck(CLimb *_parent) : CLimb(_parent)
Besides, I don't really understand how this compiled:
ptr = &hand;
hand
is not declared at all, but looks like you missed it while copy pasting the code here.
Your constructor is marked CLimb(CLimb *_parent);
meaning it takes a pointer to a CLimb but in the CNeck
constructor,
CNeck::CNeck(CLimb *_parent) : CLimb(*_parent)
you're dereferencing the pointer, which calls CLimb(CLimb&)
which is the copy constructor. Turn *_parent
into _parent
to resolve this problem. Plus you might want to define a copy constructor as well.
In other news, don't do this:
CLimb *ptr;
ptr = &hand;
Do this:
CLimb *ptr = &hand;
To avoid wasting cycles.
And you also don't need void
in the parameter list for functions which take no parameters (that's the way C does it, not C++). So for example:
CLimb(void);
CLimb(CLimb *_parent);
~CLimb(void);
Should be
CLimb();
CLimb(CLimb *_parent);
~CLimb();
I know it's not related to your question, but it's good style.
精彩评论