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
}
-------------------다음과 같은 방법으로 Sword 생성자를 정의 할 수 있습니다.
Sword(int damage) : Item( damage ) {}
또한 Item의 소멸자가 가상이고 데이터 구성원 손상이 액세스 제어를 보호해야하는 경우 더 좋을 것입니다. 예를 들면
class Item{
protected:
int damage;
public:
Item(int damage);
virtual ~Item() = default;
int GetDamage();
};
-------------------다음과 같이 파생 클래스의 생성자에서 부모의 생성자를 호출 할 수 있습니다.
Sword(int damage):
Item(damage)
{
}
출처
https://stackoverflow.com/questions/22080003