C ++ - creating a derived class and using the base class constructor

I have a base class with a constructor that requires one parameter (string). Then I have a derived class that also has its own constructor. I want to instantiate a derived class and also set the constructor parameter of the base class.

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 constructor parameter of a base class when calling a derived class.

+4
source share
3 answers

You have two options: inline:

 class DerivedClass : public BaseClass { public: DerivedClass (string b) : BaseClass(b) {} }; 

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

in the 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; }; 
+10
source

If all you want to do is build an instance of the derived class from one parameter that you pass to the constructor of the base class, you can do this:

C ++ 03 (I added an explicit and passed a const link):

 class DerivedClass : public BaseClass { public: explicit DerivedClass (const std::string& b) : BaseClass(b) {} }; 

C ++ 11 (gets all base class constructors):

 class DerivedClass : public BaseClass { public: using BaseClass::BaseClass; }; 

If you want to call different DerivedClass constructors and call the BaseClass constructor for some other value, you can also do this:

 class DerivedClass : public BaseClass { public: explicit DerivedClass () : BaseClass("Hello, World!") {} }; 
+1
source

Use this

  DerivedClass::DerivedClass(string b) : BaseClass(b) { } 

just pass the parameter directly to the base class constructor

0
source

All Articles