C++ Initialise base class

3895 views c++
10

I'm having trouble getting inheritance working.

I have a base class Entity with a derived class Item. I want to instantiate an Item with a name and description that will be passed back to the base class Entity. It's telling me: "Constructor for ‘Item’ must explicitly initialise the base class ‘Entity’ which does not have a default constructor."

Here's how I'm trying to do it in the header:

Item(string name, string description): Entity(name, description){};

And the implementation:

Item::Item (string name, string description) {
}

Cheers

answered question

Are you sure Entity has a constructor implemented or defined with Entity::Entity(string name, string description)?

Wait I'm confused on your "header" and implementation poriton.. You are already implementing it in your header? Seems like if you either copy your header to your cpp, or remove your cpp one it should work

1 Answer

8

You just need to reorder your code slightly. The : Entity(name, description) part that passes the parameters to the base class's constructor should be part of the implementation of the constructor, not part of the declaration.

That is to say, the header should contain the bit

Item(string name, string description);

And the implementation should contain:

Item::Item (string name, string description): Entity(name, description) {
}

posted this

Have an answer?

JD

Please login first before posting an answer.