+ 2

What are constructors? Why they are used?

7th Nov 2016, 2:08 AM
Ashok Chandra
Ashok Chandra - avatar
3 Answers
+ 3
Adding to Narciso's answer. A constructor is a member function with the same name as that of the class. It has no return type, not even void. The compiler creates a default constructor for each class if the programmer does not explicitly defines one. A constructor is not a function that can be called at any time as normal functions. It is called only once for an object whenever a new object of a class is created. It's called immediately after the memory for that object is assigned. Constructor just initialises the values of member variables of the class without returning anything. Since the object is already created before the constructor is called, one can call other member functions of the class from the constructor. Like other functions of c++, a constructor can also be overloaded. The default constructor created by the compiler has no argument passed to it. A programmer can write his/her own constructor without any argument which will replace the default constructor. With overloading the constructor one can write multiple constructor definitions with different arguments. Only one of these constructor can be called for each newly created object. Format: Classname *obj = new ClassName(arg1, arg2); There is another type of constructor called "copy constructor". It's usage comes into picture when you want to do a deep copy of an object. I'm not elaborating on this as of now, but it's a topic worth knowing. You can also do some other wonderful things using a constructor. For example declaring a constructor in private can give you control of the number of objects that can be created for a class. This feature can be easily utilised to implement the singleton design pattern. If you are interested you can further check out things like the order of constructors called when instantiating an object of derived class, etc.
7th Nov 2016, 3:34 PM
Navjot Singh Cheema
+ 2
Constructors are special method inside a class that is automatically executed every time you create an object of that class. Imagine you have a Person class and every object of this class need to have some defaults values, that kind of information is set in the constructor method. A default value for a person can be set in a constructor: isAlive = true
7th Nov 2016, 2:19 AM
Narciso Nuñez Arias
Narciso Nuñez Arias - avatar
0
nicely explained...thanks brotha..
7th Nov 2016, 2:25 AM
Ashok Chandra
Ashok Chandra - avatar