This is a very basic question, I searched it but i just want to ask this community that we have both constructors and methods. But normally we use constructor to initialize the variables instead of the methods. I think that both can be used to initialize variables. So what is the basic difference between both. Is there any solid reason?
this is a very basic question so bear it for sake of beginner level.
thanks in advance..
This is a very basic question, I searched it but i just want to
Share
The most important difference: When you instantiate an object it’s constructor will be invoked whereas calling a method is always optional. You therefore might forget to call your initialization method and fail to initialize everything correctly.
For example, all these normal ways of instantiating an object will call the constructor
Or if you have mandatory arguments, don’t define a default constructor and instead require construction with parameters:
This has the advantage of requiring the arguments before you even instantiate the class. So you’re forced to do:
and failing to construct with valid arguments becomes a compiler error:
So whenever possible, always err on the side of doing your initialization in a constructor. There are a few cases where a constructor might not be viable. For example, the only way to fail a constructor is by using an exception. The failure to construct may be “routine” and not truly exceptional. Also exceptions might be expensive on some architectures. Another case might be when you want to ensure that virtual methods are fully bound, which is guaranteed to be true only after construction.