I have a base class with a constructor that requires one parameter (string). Then I have a derived class which also has its' own constructor. I want to instantiate the derived class and be able to set the parameter of the base class's constructor as well.
class BaseClass {
public:
BaseClass (string a);
};
class DerivedClass : public BaseClass {
public:
DerivedClass (string b);
};
int main() {
DerivedClass abc ("Hello");
}
I'm not sure how to set the base class constructor's parameter when calling the derived class.
You have two possibilities - inline:
class DerivedClass : public BaseClass {
public:
DerivedClass (string b) : BaseClass(b) {}
};
or out 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 class instance from a single parameter that you pass to the base class constructor, you can to this:
C++03 (I have added explicit, and pass by const reference):
class DerivedClass : public BaseClass {
public:
explicit DerivedClass (const std::string& b) : BaseClass(b) {}
};
C++11 (gets all the base class constructors):
class DerivedClass : public BaseClass {
public:
using BaseClass::BaseClass;
};
If you want to call different DerivedClass
constructors and call the BaseClass
constructor to some other value, you can do it too:
class DerivedClass : public BaseClass {
public:
explicit DerivedClass () : BaseClass("Hello, World!") {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With