Default constructor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Default constructor

If only parameterised constructor is defined and then a non parameterised object is created, would it give any error? Is it necessary to define default constructor along with parameterised constructor?

5th Feb 2018, 4:39 PM
Rishabh Patel
Rishabh Patel - avatar
2 Answers
+ 9
E.g. #include <iostream> class a { public: a(int) {} }; int main() { a obj; return 0; } // Error. Class constructor a::a() is not found. // If you want to be able to initialise your class members without any parameters whilst already defined a constructor which takes parameters, you have to explicitly define another constructor which takes no arguments.
5th Feb 2018, 5:13 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
It is technically possible to define only a parameterized constructor, but you need to assign default values to all parameters. These values will then be used to initialize the object if the user does not specify any values. In any case it is a better practice (as already mentioned by @Hatsy Rei) to create a separate constructor taking no arguments. Best of luck with C++. Is a great language to my opinion!!
6th Feb 2018, 3:01 AM
Red Hawks
Red Hawks - avatar