What is a constructor in C++?
CONSTRUCTORS
Normally we invoke member function using object and also data members are initialized through objects.
C++ provides a pair of in built special(???) member functions called constructor and destructor.
RULES FOR CONSTRUCTOR
- Constructor has the same name as that of the class it belongs.
- Constructor does not return any value.i.e neither return value nor void
- In inheritance concept where properties of one class is inherited by another.Constructor is not inherited.
- Constructor is executed when an object is declared.
- Constructor can have default and can be overloaded.
- The constructor without arguments is called as default constructor.
1) Default constructor
If we are not using any arguments in a constructor, then it is called as default constructor.
Simple program to understand default constructor
2) Parameterized constructor
- using copy constructor it is possible for a programmer to declare and initialize one object using reference of another object.
- when ever a constructor is called a copy of an object is created.
- all copy constructor requires one argument, with reference to an object of that class.
Syntax:
Class_name (const class_name &object)
{
------;
Const y?????
We are copying the object values,
no changes are needed.
------;
}
Program :
Constructor overloading definition: a class contains more than one constructor which are defined with same name as the class but contains different number of arguments. depending on number of arguments the compiler executes appropriate constructor.