# C++ Constructor Inheritance

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

## 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 on other sites
I don't think it is even possible to inherit constructors.

You could try making a factory method and inheriting that.

##### Share on other sites
Quote:
 Original post by SchnozzinkobensteinI'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]