简体   繁体   中英

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?

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) {}

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 
    }

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();
};

您可以像这样从派生类的构造函数调用父级的构造函数:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM