Constructor and Destructor in OOP Qazi Abdul Samad Presented By
Contends Constructor Concept of Constructor in OOP Characteristic of Constructor Types of Constructor Constructor Overloading Destructor Charactersticks of Destructor Concept of Destructor in OOP Difference Between Constructor and Destructor
Constructor Constructor is a special type of method that is invoked when you create a new instance of a class. constructor is used to initialize the members of the class.the name of the constructor is same as the name of the class that contains it.
Concept of Constructor in OOP A constructor is a special member function whose task to initialize the object of that class. it is speacial because its name is the same as the class name. constructor is invoked whenever an object of the associated is class is created. it is called constructor because it construct the values of data member of the class.
Characteristic of Constructor They cannot be inherited, though a derived class can call the base class constructor. Like other C++ functions, Constructors can have default arguments. Constructors can not be virtual. We can not refer to their addresses. They make ‘implicit calls’ to the operators new and delete when memory allocation is required.
Types of Constructor 1. Default Constructor : A constructor that accepts no parameters is called Default Constructor. 2. Parameterized Constructor : The constructor that can take arguments is called as Parameterized Constructor. 3. Copy Constructor : A constructor can accept a reference to its own class as a parameter which is called Copy Constructor
Example of Default Constructor ;
Example of Parameterized constructor ;
Example of Copy constructor;
Constructor Overloading The process of declaring multiple constructor with the same name but different parameters is known as constructor overloading. the constructor with same name must differ in one of the following ways 1. number of parameters 2. type of parameters 3. sequence of parameters its covenient to be able to gives values to member variables of a class when the objects is created.
Example
Destructor A destructor, as the name implies is used to destroy the objects that have been created by a constructor. Like a constructor the destructor is also a special member function whose name is the same as the class name but is preceded by a tilde (~). A destructor never takes any argument nor does it return any value. Example the destructor for the class integer can be defined as shown below ~integer( ) { }
Example of Destructor
Characteristic OF Destructor Destructor function are invoked automatically when the objects are destroyed. if the class has a destructor each object of that class will be de- intialized before the objects goes out of scope. destructor function obeys the usual access rules. no arrguments can be provided to a destructor neither does it returns any value. they can not be inherited. a destructor may not be static..