SlideShare a Scribd company logo
Constructors/ Destructor
Muhammad Hammad Waseem
m.hammad.wasim@gmail.com
Constructors
• Member functions can be used to give values to the data items in an object.
Sometimes, however, it’s convenient if an object can initialize itself when it’s first
created, without requiring a separate call to a member function.
• A type of member function that is automatically executed when an object of the
class is created is known as constructor.
• The constructor has
• no return type and
• has the same name that of class name.
• The constructor can work as normal function but it cannot return any value.
• It is normally defined in classes to initialize data members.
• It construct the object, therefore it is called constructor.
Syntax
• The syntax of declaring constructor is as follows:
name()
{
Body of constructor;
}
• name()
• Indicates the name of the constructor.
• The name must be same as the name of the class in which the constructor is
declared.
Example
#include <iostream.h>
#include <conio.h>
class Hello
{
private:
int n;
public:
Hello()
{ cout<<”Object is created”; }
};
void main()
{
Hello x,y,z;
getch();
}
In this program, three objects are
created, so the constructor will be
called three times and display
OUTPUT
Object is created
Object is created
Object is created
Same Name as the Class, No Return Type
• There are some unusual aspects of constructor functions.
• First, it is no accident that they have exactly the same name as the class of
which they are members.
• Second, no return type is used for constructors.
• Why not? Since the constructor is called automatically by the system, there’s no program
for it to return anything to; a return value wouldn’t make sense.
• These are two ways, the compiler knows that they are constructors.
Default Constructor
• An implicit no-argument constructor is built into every program
automatically by the compiler, and this constructor creates the objects,
even though we do not define it in the class. This no-argument constructor
is called the default constructor.
• If it weren’t created automatically by the compiler, we wouldn’t be able to
create objects of a class for which no constructor was defined.
• Often we want to initialize data members in the default (no-argument)
constructor as well.
• If we let the default constructor do it, we don’t really know what values the data
members may be given.
• If we care what values they may be given, we need to explicitly define the
constructor.
Example
#include <iostream.h>
#include <conio.h>
class Number
{
private:
int n,m;
public:
Number() //Default Constructor Explicit Definition
{ n = m = 100; }
Avg()
{ cout<<“Average of two numbers=”<<(n+m)/2; }
};
void main()
{
Number x;
x.avg();
getch();
}
Passing Parameters to Constructor
• Constructor can have parameters as normal functions do.
• The method of passing the parameters to a constructor is same as passing parameters to a
normal function.
• The only difference is that parameters are passed to the constructor when the object is declared.
• The parameters are written in parenthesis along with the object name in declaration statement.
• Syntax (parameterized constructor):
Constructor_Name(parameter_list)
{
Constructor body;
}
• Syntax (creating object):
Class_Name object_name(parameter_list);
Example: Write a class TV that contains attributes of Brand Name, Model and Retail Price.
Write a method to display all attributes and a method to change the attributes. Also write constructor
to initialize all the attributes.
#include<conio.h>
#include<iostream.h>
#include<string.h>
class TV {
private:
char BrandName[20], Model[10];
float Price;
public:
TV(char Brand[], char mod[], float pr)
{
// strcpy() is used to copy one string to another.
strcpy(BrandName,Brand);
strcpy(Model,mod);
Price=pr;
}
void Change(char Brand[], char mod[], float pr)
{
strcpy(BrandName,Brand);
strcpy(Model,mod);
Price=pr;
}
void Display()
{
cout<<"nBrand Name="<<BrandName<<endl;
cout<<"Model Name="<<Model<<endl;
cout<<"Retail Price="<<Price<<endl;
}
};
void main()
{
TV test("Sony","2010", 2000);
test.Display();
test.Change("Toshiba","2014",15000);
cout<<"nAfter Changing Values of Object";
test.Display();
getch();
}
Default Copy Constructor
• A type of constructor that is used to initialize an object with another object of the same type is known as
default copy constructor or copy constructor.
• Its name is “default copy constructor” because it is available by default in all classes. The user does not need
to write this constructor.
• It accepts a single object of the same type as parameter.
• The parameter for default copy constructor can be given in parenthesis or using assignment operator.
• Syntax
class_name object_name (parameter); OR
class_name object_name = parameter;
• class_name
• is the name of class and indicates the type of object to be created.
• Object_name
• indicates the name of object to be created.
• Parameter
• indicates the name of parameter that is passed to default copy constructor. The values of data members of parameter object
are copied to the data members of the new object. The type of new object and parameter object must be same.
Constructor Overloading
• The process of declaring multiple constructors with same name but
different parameters is known as constructor overloading.
• The constructors with same name must differ in one of the following
ways:
• Number of parameters
• Type of parameter
• Sequence of parameters
• It’s convenient to be able to give values to member variables of a
class when the object is created.
Example
#include<iostream.h>
#include<conio.h>
class Over
{
private:
int num;
char ch;
public:
Over() //default constructor
{ num=0; ch=‘x’; }
Over(int n, char c)//Overloaded constructor
{ num=n; ch=c; }
void Show()
{
cout<<“num=”<<num<<endl<<“ch=”<<ch;
}
};
void main()
{
Over first,second(100,’p’);
cout<<“The Content of First”<<endl;
first.Show();
cout<<“The Content of Second”<<endl;
second.Show();
getch();
}
Destructors
• We’ve seen that a special member function—the constructor—is called automatically when an
object is first created.
• You might guess that another function is called automatically when an object is destroyed. Such a
function is called a destructor.
• A destructor has
• same name as the constructor or class name
• No return type
• Not accept any parameters.
• preceded by a tilde sign (~).
• Syntax
~ name()
{
Destructor body
}
Example
#include<iostream.h>
#include<conio.h>
class Foo
{
private:
int data;
public:
Foo() //constructor
{
cout<<”Object Created”<<endl;
}
~Foo() //destructor
{
cout<<”Object Destroyed”<<endl;
}
};
int main()
{ Foo f1,f2; return 0; }
• OUTPUT:
Object Created
Object Created
Object Destroyed
Object Destroyed

More Related Content

PPTX
[OOP - Lec 20,21] Inheritance
PPTX
[OOP - Lec 09,10,11] Class Members & their Accessing
PPTX
[OOP - Lec 18] Static Data Member
PPTX
[OOP - Lec 04,05] Basic Building Blocks of OOP
PPTX
Constructor in java
PPTX
Java constructors
PPT
Constructors
PPTX
Constructor overloading & method overloading
[OOP - Lec 20,21] Inheritance
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 18] Static Data Member
[OOP - Lec 04,05] Basic Building Blocks of OOP
Constructor in java
Java constructors
Constructors
Constructor overloading & method overloading

What's hot (20)

PPTX
constructors in java ppt
PPTX
Methods and constructors in java
PPTX
Data members and member functions
PPTX
Constructor and Destructor
PPTX
Classes and Objects in C#
PPT
vb.net Constructor and destructor
PPT
constructor and destructor-object oriented programming
PPTX
Static Data Members and Member Functions
PPTX
Constructor and destructor in oop
PPTX
Java Constructors | Java Course
PDF
Constructor & destructor
PPT
C++ classes
PPT
Constructor
PPT
Class and object in c++
PPT
Class and object in C++
PPTX
C++ classes
PPTX
Classes and objects
PPTX
Constructor & destructor
PPTX
Classes and objects
PPTX
Classes in c++ (OOP Presentation)
constructors in java ppt
Methods and constructors in java
Data members and member functions
Constructor and Destructor
Classes and Objects in C#
vb.net Constructor and destructor
constructor and destructor-object oriented programming
Static Data Members and Member Functions
Constructor and destructor in oop
Java Constructors | Java Course
Constructor & destructor
C++ classes
Constructor
Class and object in c++
Class and object in C++
C++ classes
Classes and objects
Constructor & destructor
Classes and objects
Classes in c++ (OOP Presentation)
Ad

Viewers also liked (11)

PPTX
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
PPTX
[OOP - Lec 19] Static Member Functions
PPTX
[OOP - Lec 06] Classes and Objects
PPTX
Data Structures - Lecture 3 [Arrays]
PPTX
[OOP - Lec 03] Programming Paradigms
PPTX
[OOP - Lec 01] Introduction to OOP
PPTX
[OOP - Lec 02] Why do we need OOP
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
PPTX
[OOP - Lec 07] Access Specifiers
PPTX
[OOP - Lec 08] Encapsulation (Information Hiding)
PPTX
Data structure and its types
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 19] Static Member Functions
[OOP - Lec 06] Classes and Objects
Data Structures - Lecture 3 [Arrays]
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 02] Why do we need OOP
Data Structures - Lecture 9 [Stack & Queue using Linked List]
[OOP - Lec 07] Access Specifiers
[OOP - Lec 08] Encapsulation (Information Hiding)
Data structure and its types
Ad

Similar to [OOP - Lec 13,14,15] Constructors / Destructor and its Types (20)

PPTX
OOP-Lecture-05 (Constructor_Destructor).pptx
PPT
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
PPTX
Constructors in C++.pptx
PPTX
Constructor and desturctor
PDF
Constructors or destructors unit(II).pdf
PPTX
Constructors and Destructors
PDF
Constructors and destructors
PDF
Constructors & Destructors [Compatibility Mode].pdf
PPT
Constructors and destructors in C++
DOCX
Constructor-Types of Constructor:default,parameterized,copy constructor-Destr...
PDF
Constructor and Destructor
PPTX
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
PPTX
Constructor in c++
PDF
Constructor and Destructor.pdf
PPTX
C++Constructors
PPT
ConsTRUCTION AND DESTRUCTION
PPTX
Constructors and Destructors in C++.pptx
PPTX
constructors and destructors
PPT
Constructor and destructor in C++
PPTX
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Constructors in C++.pptx
Constructor and desturctor
Constructors or destructors unit(II).pdf
Constructors and Destructors
Constructors and destructors
Constructors & Destructors [Compatibility Mode].pdf
Constructors and destructors in C++
Constructor-Types of Constructor:default,parameterized,copy constructor-Destr...
Constructor and Destructor
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
Constructor in c++
Constructor and Destructor.pdf
C++Constructors
ConsTRUCTION AND DESTRUCTION
Constructors and Destructors in C++.pptx
constructors and destructors
Constructor and destructor in C++
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx

More from Muhammad Hammad Waseem (18)

PDF
[ITP - Lecture 17] Strings in C/C++
PDF
[ITP - Lecture 16] Structures in C/C++
PDF
[ITP - Lecture 15] Arrays & its Types
PDF
[ITP - Lecture 14] Recursion
PDF
[ITP - Lecture 13] Introduction to Pointers
PDF
[ITP - Lecture 12] Functions in C/C++
PDF
[ITP - Lecture 11] Loops in C/C++
PDF
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
PDF
[ITP - Lecture 09] Conditional Operator in C/C++
PDF
[ITP - Lecture 08] Decision Control Structures (If Statement)
PDF
[ITP - Lecture 07] Comments in C/C++
PDF
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
PDF
[ITP - Lecture 05] Datatypes
PDF
[ITP - Lecture 04] Variables and Constants in C/C++
PDF
[ITP - Lecture 03] Introduction to C/C++
PDF
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
PDF
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
PPTX
Data Structures - Lecture 10 [Graphs]
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 14] Recursion
[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 05] Datatypes
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
Data Structures - Lecture 10 [Graphs]

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
master seminar digital applications in india
PPTX
Cell Types and Its function , kingdom of life
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Classroom Observation Tools for Teachers
PDF
01-Introduction-to-Information-Management.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Lesson notes of climatology university.
PPTX
Cell Structure & Organelles in detailed.
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
Anesthesia in Laparoscopic Surgery in India
PPH.pptx obstetrics and gynecology in nursing
STATICS OF THE RIGID BODIES Hibbelers.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
master seminar digital applications in india
Cell Types and Its function , kingdom of life
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Classroom Observation Tools for Teachers
01-Introduction-to-Information-Management.pdf
Microbial disease of the cardiovascular and lymphatic systems
Lesson notes of climatology university.
Cell Structure & Organelles in detailed.
human mycosis Human fungal infections are called human mycosis..pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
TR - Agricultural Crops Production NC III.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
O5-L3 Freight Transport Ops (International) V1.pdf

[OOP - Lec 13,14,15] Constructors / Destructor and its Types

  • 1. Constructors/ Destructor Muhammad Hammad Waseem m.hammad.wasim@gmail.com
  • 2. Constructors • Member functions can be used to give values to the data items in an object. Sometimes, however, it’s convenient if an object can initialize itself when it’s first created, without requiring a separate call to a member function. • A type of member function that is automatically executed when an object of the class is created is known as constructor. • The constructor has • no return type and • has the same name that of class name. • The constructor can work as normal function but it cannot return any value. • It is normally defined in classes to initialize data members. • It construct the object, therefore it is called constructor.
  • 3. Syntax • The syntax of declaring constructor is as follows: name() { Body of constructor; } • name() • Indicates the name of the constructor. • The name must be same as the name of the class in which the constructor is declared.
  • 4. Example #include <iostream.h> #include <conio.h> class Hello { private: int n; public: Hello() { cout<<”Object is created”; } }; void main() { Hello x,y,z; getch(); } In this program, three objects are created, so the constructor will be called three times and display OUTPUT Object is created Object is created Object is created
  • 5. Same Name as the Class, No Return Type • There are some unusual aspects of constructor functions. • First, it is no accident that they have exactly the same name as the class of which they are members. • Second, no return type is used for constructors. • Why not? Since the constructor is called automatically by the system, there’s no program for it to return anything to; a return value wouldn’t make sense. • These are two ways, the compiler knows that they are constructors.
  • 6. Default Constructor • An implicit no-argument constructor is built into every program automatically by the compiler, and this constructor creates the objects, even though we do not define it in the class. This no-argument constructor is called the default constructor. • If it weren’t created automatically by the compiler, we wouldn’t be able to create objects of a class for which no constructor was defined. • Often we want to initialize data members in the default (no-argument) constructor as well. • If we let the default constructor do it, we don’t really know what values the data members may be given. • If we care what values they may be given, we need to explicitly define the constructor.
  • 7. Example #include <iostream.h> #include <conio.h> class Number { private: int n,m; public: Number() //Default Constructor Explicit Definition { n = m = 100; } Avg() { cout<<“Average of two numbers=”<<(n+m)/2; } }; void main() { Number x; x.avg(); getch(); }
  • 8. Passing Parameters to Constructor • Constructor can have parameters as normal functions do. • The method of passing the parameters to a constructor is same as passing parameters to a normal function. • The only difference is that parameters are passed to the constructor when the object is declared. • The parameters are written in parenthesis along with the object name in declaration statement. • Syntax (parameterized constructor): Constructor_Name(parameter_list) { Constructor body; } • Syntax (creating object): Class_Name object_name(parameter_list);
  • 9. Example: Write a class TV that contains attributes of Brand Name, Model and Retail Price. Write a method to display all attributes and a method to change the attributes. Also write constructor to initialize all the attributes. #include<conio.h> #include<iostream.h> #include<string.h> class TV { private: char BrandName[20], Model[10]; float Price; public: TV(char Brand[], char mod[], float pr) { // strcpy() is used to copy one string to another. strcpy(BrandName,Brand); strcpy(Model,mod); Price=pr; } void Change(char Brand[], char mod[], float pr) { strcpy(BrandName,Brand); strcpy(Model,mod); Price=pr; } void Display() { cout<<"nBrand Name="<<BrandName<<endl; cout<<"Model Name="<<Model<<endl; cout<<"Retail Price="<<Price<<endl; } }; void main() { TV test("Sony","2010", 2000); test.Display(); test.Change("Toshiba","2014",15000); cout<<"nAfter Changing Values of Object"; test.Display(); getch(); }
  • 10. Default Copy Constructor • A type of constructor that is used to initialize an object with another object of the same type is known as default copy constructor or copy constructor. • Its name is “default copy constructor” because it is available by default in all classes. The user does not need to write this constructor. • It accepts a single object of the same type as parameter. • The parameter for default copy constructor can be given in parenthesis or using assignment operator. • Syntax class_name object_name (parameter); OR class_name object_name = parameter; • class_name • is the name of class and indicates the type of object to be created. • Object_name • indicates the name of object to be created. • Parameter • indicates the name of parameter that is passed to default copy constructor. The values of data members of parameter object are copied to the data members of the new object. The type of new object and parameter object must be same.
  • 11. Constructor Overloading • The process of declaring multiple constructors with same name but different parameters is known as constructor overloading. • The constructors with same name must differ in one of the following ways: • Number of parameters • Type of parameter • Sequence of parameters • It’s convenient to be able to give values to member variables of a class when the object is created.
  • 12. Example #include<iostream.h> #include<conio.h> class Over { private: int num; char ch; public: Over() //default constructor { num=0; ch=‘x’; } Over(int n, char c)//Overloaded constructor { num=n; ch=c; } void Show() { cout<<“num=”<<num<<endl<<“ch=”<<ch; } }; void main() { Over first,second(100,’p’); cout<<“The Content of First”<<endl; first.Show(); cout<<“The Content of Second”<<endl; second.Show(); getch(); }
  • 13. Destructors • We’ve seen that a special member function—the constructor—is called automatically when an object is first created. • You might guess that another function is called automatically when an object is destroyed. Such a function is called a destructor. • A destructor has • same name as the constructor or class name • No return type • Not accept any parameters. • preceded by a tilde sign (~). • Syntax ~ name() { Destructor body }
  • 14. Example #include<iostream.h> #include<conio.h> class Foo { private: int data; public: Foo() //constructor { cout<<”Object Created”<<endl; } ~Foo() //destructor { cout<<”Object Destroyed”<<endl; } }; int main() { Foo f1,f2; return 0; } • OUTPUT: Object Created Object Created Object Destroyed Object Destroyed