[ACCEPTED]-C++ - Instantiating derived class and using base class's constructor-inheritance
Accepted answer
You have two possibilities - inline:
class DerivedClass : public BaseClass {
public:
DerivedClass (string b) : BaseClass(b) {}
};
or out 1 of line:
class DerivedClass : public BaseClass {
public:
DerivedClass (string b);
};
/* ... */
DerivedClass::DerivedClass(string b) : BaseClass(b)
{}
more examples:
class DerivedClass : public BaseClass {
public:
DerivedClass(int a, string b, string c);
private:
int x;
};
DerivedClass::DerivedClass(int a, string b, string c) : BaseClass(b + c), x(a)
{}
on initializer lists:
class MyType {
public:
MyType(int val) { myVal = val; } // needs int
private:
int myVal;
};
class DerivedClass : public BaseClass {
public:
DerivedClass(int a, string b) : BaseClass(b)
{ x = a; } // error, this tries to assign 'a' to default-constructed 'x'
// but MyType doesn't have default constructor
DerivedClass(int a, string b) : BaseClass(b), x(a)
{} // this is the way to do it
private:
MyType x;
};
If all you want to do is construct a derived 8 class instance from a single parameter that 7 you pass to the base class constructor, you 6 can to this:
C++03 (I have added explicit, and 5 pass by const reference):
class DerivedClass : public BaseClass {
public:
explicit DerivedClass (const std::string& b) : BaseClass(b) {}
};
C++11 (gets all 4 the base class constructors):
class DerivedClass : public BaseClass {
public:
using BaseClass::BaseClass;
};
If you want 3 to call different DerivedClass
constructors and call 2 the BaseClass
constructor to some other value, you 1 can do it too:
class DerivedClass : public BaseClass {
public:
explicit DerivedClass () : BaseClass("Hello, World!") {}
};
Use this
DerivedClass::DerivedClass(string b)
: BaseClass(b)
{
}
just pass the parameter direct to 1 the base class constructor
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.