Sign in to follow this  
Schnozzinkobenstein

C++ Constructor Inheritance

Recommended Posts

I'm trying to inherit a constructor from a base class. Am I doing this correctly? Also, why do I have to end my prototype with "{}" instead of ";" I'd think I'd be redefining if I did that. Character.h:
class Character{
public:
	Character(	float charPosX,float charPosY,float charPosZ,
			float charRotX,float charRotY,float charRotZ);
private:
	float pos[3];
	float rot[3];
};
Character.cpp:
Character::Character(	float charPosX,float charPosY,float charPosZ,
			float charRotX,float charRotY,float charRotZ)
{
	pos[X]=charPosX;
	pos[Y]=charPosY;
	pos[Z]=charPosZ;
	rot[X]=charRotX;
	rot[Y]=charRotY;
	rot[Z]=charRotZ;
}
Player.h
class Player : public Character{
public:
	Player(	float charPosX,float charPosY,float charPosZ,
		float charRotX,float charRotY,float charRotZ)
	:Character(	charPosX,charPosY,charPosZ,
			charRotX,charRotY,charRotZ){}
};
Player.cpp:
Player::Player(	float charPosX,float charPosY,float charPosZ,
		float charRotX,float charRotY,float charRotZ){}

Share this post


Link to post
Share on other sites
mattd    1078
Quote:
Original post by Schnozzinkobenstein
I'm trying to inherit a constructor from a base class. Am I doing this correctly?

You don't (and can't) inherit constructors in C++. Instead, you explicitly call the superclass constructor of your choice in your class's constructor's initializer list. This is what you are doing here correctly, except for one point: the "{}" means that the constructor described in Player.h isn't just the declaration of it, but its definition. The braces are the constructor's (empty) body. Therefore you don't need to (and can't) define it again in Player.cpp. EDIT: If you do want to define it externally from the class definition in the header file, move the initializer list to that external definition, like so:

Player.h

class Player : public Character{
public:
Player( float charPosX,float charPosY,float charPosZ,
float charRotX,float charRotY,float charRotZ);
};



Player.cpp

Player::Player( float charPosX,float charPosY,float charPosZ,
float charRotX,float charRotY,float charRotZ)
:Character( charPosX,charPosY,charPosZ,
charRotX,charRotY,charRotZ)
{

}



Quote:
Also, why do I have to end my prototype with "{}" instead of ";" I'd think I'd be redefining if I did that.

Right, see above.

[Edited by - mattd on November 7, 2009 12:09:28 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this