Reputation: 481
class class1 {
public:
class1(int x);
};
class class2 : public class1 {
};
Can I do:
class2 my_class2(10);
Or do I have to define the constructor again for class2
(even though it does exactly the same thing)?
Upvotes: 3
Views: 58
Reputation: 15997
Since C++17, you can directly call public base-class constructors via aggregate initialization - without adding any code to the classes:
class2 my_class2{2}; // Note the curly braces!
Upvotes: 3
Reputation: 24738
Since C++11 constructors can be inherited:
class class2 : public class1 {
public:
using class1::class1;
};
Otherwise you have to do the following:
class class2 : public class1 {
public:
class2(int x): class1(x) {}
};
A constructor of the base class has to be called anyway when constructing an object of the derived class.
Upvotes: 6