I am noticing a lot in my data structures class that they are declaring constructors and destructors. This is for C++ by the way.
Asked
Active
Viewed 612 times
1
-
Does this answer your question? [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – Silvio Mayolo Feb 15 '21 at 22:54
-
1This is duplicate: [Should i define the default constructor? \[closed\]](https://stackoverflow.com/questions/22184060/should-i-define-the-default-constructor) – drantini Feb 15 '21 at 22:55
-
1The answer is going to depend on what state you expect your class-objects to be in after they are constructed. If you are okay with the default behavior that you get without a constructor, then there's no need to write a constructor; OTOH if you need to specify on-construction behavior explicitly, writing a constructor is the way to do that. – Jeremy Friesner Feb 15 '21 at 22:57
-
Does this answer your question? [Should i define the default constructor?](https://stackoverflow.com/questions/22184060/should-i-define-the-default-constructor) – lucasreta Feb 15 '21 at 23:09
1 Answers
2
Do these objects allocate and retain memory? Do they allocate resources that must be released?
If so, yes, a destructor is required. If not, no.
This is all part of understanding C++ RIAA which is the defining methodology here.
Constructors aren't necessary for struct
, those are often treated as "dumb data" with no built-in smarts, but they are usually necessary for class
as you're going to be calling new
on those with an expectation that the data is properly initialized, not zeroed.

tadman
- 208,517
- 23
- 234
- 262