Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing in Constructor

I have seen lots of codes where the coders define an init() function for classes and call it the first thing after creating the instance.

Is there any harm or limitation of doing all the initializations in Constructor?

like image 230
MBZ Avatar asked May 08 '12 07:05

MBZ


People also ask

What is initialization in constructor?

Explicit initialization with constructors (C++ only) A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

How do you initialize a variable in a constructor?

A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.

Why do we initialize variable in constructor?

It makes sense to initialize the variable at declaration to avoid redundancy. It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors.

Are constructors used for initialization?

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.


1 Answers

Usually for maintainability and to reduce code size when multiple constructors call the same initialization code:

class stuff 
{
public:
    stuff(int val1) { init(); setVal = val1; }
    stuff()         { init(); setVal = 0; }

    void init()     { startZero = 0; }

protected:
    int setVal;
    int startZero;
};
like image 99
dag Avatar answered Sep 22 '22 20:09

dag