user3316633
user3316633

Reputation: 137

C++ calling an inherited constructor

I have a header file, "Item.h", which "Sword.h" inherits, like this:

#ifndef SWORD_H
#define SWORD_H

#include "Item.h"

class Sword: public Item {
public:
    Sword(int damage);
    ~Sword();
};
#endif

My Item.h is this:

#ifndef ITEM_H
#define ITEM_H

class Item{
public:
   int damage;

   Item(int damage);
   int GetDamage();
};
#endif

And then I have a file, "Sword.cpp", that I want to call the Item constructor from (this is the Item.cpp):

#include "Item.h"

Item::Item(int damage)
{
   this->damage = damage;
}

int Item::GetDamage()
{
   return damage;
}

I basically want Sword.cpp to be a child class of Item.cpp, so that I can use Item's functions, and set variables such as Damage from Sword.cpp. I've been told there is no way to inherit constructors in C++ though, so how could I do this? Some answers seem to use the explicit keyword, but I can never get it to work.

Any help please?

Upvotes: 0

Views: 1184

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You can define the Sword constructor the following way

Sword(int damage) : Item( damage ) {}

Also it would be better if the destructor of Item were virtual and data member damage should have access control protected. For example

class Item{
protected:
   int damage;
public:
   Item(int damage);
   virtual ~Item() = default;
   int GetDamage();
};

Upvotes: 1

Zebra North
Zebra North

Reputation: 11492

You can call the parent's constructor from your derived class's constructor like this:

Sword(int damage): Item(damage) { }

Upvotes: 0

Merlevede
Merlevede

Reputation: 8170

You don't inherit the constructor because the constructor has the same name as the class (and obviously parent and child must have different names). But you can use the parent's constructor in the child's constructor

    Sword()
    : Item(3)    // Call the superclass constructor and set damage to 3
    {
        // do something 
    }

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

You can actually inherit constructors. It is all-or nothing though, you can't select which ones. This is how you do it:

class Sword: public Item {
public:
    using Item::Item;
    ~Sword();
};

If you are stuck with a pre-C++11 compiler, then you need to declare the constructor and implement it yourself. This would be the implementation in Sword.cpp:

Sword::Sword(int damage) : Item(damage) {}

Upvotes: 3

Related Questions