Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a struct's default constructor to be called?

Is there any way to prevent the default constructor of a struct to be called?

I have several structs in my project and some of them I can not let the default constructor to be called at any circumstances (that will be cause a lot of unwanted behaviour in my code).

PS.: Any solution that just indicates me when coding that some of that special structs (that can not be instantiated with the default constructor) are being instantiate "wrongly" is fine for me. A simple compiler warning should be enough for my case!

like image 544
andresantacruz Avatar asked Apr 13 '16 16:04

andresantacruz


Video Answer


1 Answers

You cannot.

By nature,

  • all fields of a struct must be initialized to some value.
  • a struct cannot have a parameter-less constructor
  • the parameter-less constructor will be implicitly called, there's no way around it.

Either use a class if you need such behavior or review your design.

like image 94
aybe Avatar answered Sep 28 '22 07:09

aybe