Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to have a default constructor?

Tags:

c++

oop

class

Say I have a class. I want it to have a constructor that takes certain arguments, so I make one. Do I still need to have a constructor that has no arguments (default constructor) even if I don't need it? In other words, do i have to include Class() as a member function even if I don't need it?

like image 577
dfg Avatar asked Sep 04 '25 17:09

dfg


2 Answers

No, if you don't need it then you don't need it.

You only need it if you want to be able to default-initialise the class. Often you don't want that - you only want objects to exist if they were correctly initialised with the constructor(s) you wrote - which is why declaring your own constructor removes the implicit default constructor.

like image 175
Mike Seymour Avatar answered Sep 07 '25 09:09

Mike Seymour


No. Make a class that does what you need, not one that adheres to cargo cults for no reason. Rubber duck the class if in doubt.

like image 41
Kerrek SB Avatar answered Sep 07 '25 09:09

Kerrek SB