Constructors and Destructors
Constructor:- A constructor is a special member function with the same name as its class name and is used to initialize the data members of the class. Constructor is invoked automatically when an object of a class is created. Constructor do not return any value not even void. Constructor must be defined in public section.
Types of Constructors
1. Default Constructor (No argument constructor):- A default constructor accepts no parameters. When no constructor is defined in the class, compiler provides the default constructor.
2. Parameterized Constructor (Overloaded Constructor):- Parameterized constructor accepts parameters and is used to assign these parameters to the data members of the class. There may be many definitions of the parameterized constructor depending upon the type and number of parameters passed to the constructor and so it is also called overloaded constructor.
3. Copy Constructor:-A constructor that accepts a reference to an instance of its own class as an argument is called as Copy Constructor. A copy constructor is used to create new object with the similar values of existing object. A copy constructor is invoked when one object is defined and initialized with another object of the same class.
Syntax for declaration of copy constructor:-
classname(classname &obj)
for example:- Student(Student &s)
Note 1 : When parameterized constructor is defined one must define the default constructor also, otherwise error may occur when a call to default constructor is made.
Note 2: When multiple constructors are defined for a class it is also known as constructor overloading.