What is Constructors and Destructors in C++ (Explained with Example along with difference.)

PallaviSeth6 1,478 views 9 slides Jul 23, 2018
Slide 1
Slide 1 of 9
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9

About This Presentation

This slide will help you to understand the concept of constructors and destuctors in C++. This slide is made by keeping not only the final exam point of view but Mcq type questions which are quite often seen in competitive exams.


Slide Content

Welcome

Constructor and destructor What is Constructor? Constructor is basically a special member function having same name as that of class.

Properties of constructors A constructor has the same name as that of class Constructor doesn’t have a return type not even void Like normal functions Constructor have default argument. They may not be static They cannot be inherited. They are executed automatically whenever objects of class are created. We can declare more than one constructor in a class

Syntax of constructor in C++ class CLASSNAME { ……………. } Public: CLASSNAME([parameter list]) { ……………. } }; class student { ……………. } Public: student () { ……………. } };

What is destructor? A destructor is a member function having same name as that of Constructor but followed by a tilde(~) symbol .

Properties of destructor A destructor has the same name as that of a class or constructor to which it belong followed by tilde sign. It is executed automatically and is used to destroy the objects of class. It takes neither parameter nor any value. There is only one constructor in a class It cannot be overloaded. It cannot be declared static or const. They cannot be inherited.

Syntax of destructor in C++ Class CLASSNAME { ……….. Public: CLASSNAME() //DESTRUCTOR DECLARATION { ……………….. } ~CLASSNAME() // DESTRUCTOR DEFINITION { } };

DIFFERENCE BETWEEN CONTRUCTOR & DESTRUCTOR Constructor Constructor allocates the memory They can have arguments Overloading is possible No special symbol needed for recognition Classname(arguments) { // body of Constructor } DESTRUCTOR Destructor deallocates the memory They cannot have arguments. No overloading possible Tilde symbol needed for recognition ~classname() { ………………… }

thanks