SlideShare uma empresa Scribd logo
1 de 14
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

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Constructor
ConstructorConstructor
Constructor
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Constructor and destructor in oop
Constructor and destructor in oop Constructor and destructor in oop
Constructor and destructor in oop
 
Java Constructors | Java Course
Java Constructors | Java CourseJava Constructors | Java Course
Java Constructors | Java Course
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
C++ classes
C++ classesC++ classes
C++ classes
 
Constructor
ConstructorConstructor
Constructor
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C++ classes
C++ classesC++ classes
C++ classes
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 

Destaque (11)

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

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

CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
Asfand Hassan
 

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

constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructor and destructor
Constructor and destructorConstructor and destructor
Constructor and destructor
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Oops
OopsOops
Oops
 
Constructor and Destructor.pdf
Constructor and Destructor.pdfConstructor and Destructor.pdf
Constructor and Destructor.pdf
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 
constructor.ppt
constructor.pptconstructor.ppt
constructor.ppt
 
Constructors in C++.pptx
Constructors in C++.pptxConstructors in C++.pptx
Constructors in C++.pptx
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
C++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversionC++ - Constructors,Destructors, Operator overloading and Type conversion
C++ - Constructors,Destructors, Operator overloading and Type conversion
 
constructor in object oriented program.pptx
constructor in object oriented program.pptxconstructor in object oriented program.pptx
constructor in object oriented program.pptx
 
106da session5 c++
106da session5 c++106da session5 c++
106da session5 c++
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 

Mais de Muhammad Hammad Waseem

Mais de Muhammad Hammad Waseem (18)

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

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Último (20)

SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

[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