C++ Constructor Inheritance

Started by
1 comment, last by mattd 14 years, 5 months ago
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){}
--------------------Configuration: error maker - Win32 Debug--------------------Compiling...error maker.cppLinking...error maker.exe - 1 error(s), 0 warning(s)
Advertisement
I don't think it is even possible to inherit constructors.

You could try making a factory method and inheriting that.
I trust exceptions about as far as I can throw them.
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]

This topic is closed to new replies.

Advertisement