SlideShare une entreprise Scribd logo
1  sur  33
 we know that the objects are allocated memory per
instance basis when they are created. But the question is
that who will allocate memory to object at the time of
creation?.
 The c++ provides solution of these problem is
constructor, which enables an object initialize itself when
it is created.
 For example, if we create object student s1 then the
compiler automatically supplies the constructor known as
default constructor as follows:
student
{
} C++ lecture notes by Hansa Halai
 Characteristic of constructor:
› Its name is same as class name.
› It has no arguments
› Its does not have any return type.
› Body part is null(no statement in body).
› It is called automatically when object is created.
› They should be declare in public section.
C++ lecture notes by Hansa Halai
 Default constructor is constructor that takes no arguments.
The default constructor for class student has form
student::student().
 A constructor which has all default arguments, for example
student::student( int x=0) is also default constructor, since it
can be called with no argument.
 Ex:
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point() //default constructor
{
}
void set_point()
{
x=0;
y=0;
} C++ lecture notes by Hansa Halai
void set_point(int x1,int y1)
{
x=x1;
y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2;
p1.set_point();
p2.set_point(1,2);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P1 is = ";
p2.put_point();
return 0; }
C++ lecture notes by Hansa Halai
 In above program, we have written default constructor
that is exactly same as the compiler provide.
 We can write initialization statement in body part of
default constructor which is allowed.
 For that constructor first create the object by allocating
memory and then execute statements in body of
constructor, if provided.
 If we provide the initialization statements in body of
constructor, the object gets initialized by default values
provided in body at the time of creating object as
constructor.
 for Ex:
point() // default constructor with initialization
{
X=0;
Y=0;
}
C++ lecture notes by Hansa Halai
 The default constructor are used initialize the object with
default values.
 But all objects are not initialized to same values rather
different object needs to be initialized by different values.
 To initialize object with different values, we use function like
getvalue().
 C++ provide feature is parameterize constructor to solve
this problem.
 The constructor that can take arguments are called
parameterize constructor .
 The advantage of using parameterize constructor that we
can pass the value at the time of defining object with which
the compiler automatically calls it
C++ lecture notes by Hansa Halai
C++ lecture notes by Hansa Halai
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point() // default constructor
{
x=0;
y=0;
}
point(int x1,int y1) // parameterize constructor
{
x=x1;
y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3,9);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
return 0;
}
C++ lecture notes by Hansa Halai
 In a class if we use more than one constructor with each
constructor are different, this concept is called constructor
overloading.
 Ex:
C++ lecture notes by Hansa Halai
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point() //default constructor
{
x=0;
y=0;
}
point(int x1) //one parameter constructor
{
x=x1;
y=0;
}
point(int x1,int y1) //two parameter constructor
{
x=x1;
y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
C++ lecture notes by Hansa Halai
int main()
{
point p1,p2(3),p3(3,4);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}
C++ lecture notes by Hansa Halai
 A argument is a value given in the declaration that the
compiler automatically insert if you don’t provide a value
in function call.
 It is possible to define constructor with default argument.
 Ex:
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point()
{
x=0;
y=0; }
C++ lecture notes by Hansa Halai
point(int x1,int y1=1)
{
x=x1;
y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(3),p3(9);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}
C++ lecture notes by Hansa Halai
 As variable , object can be also dynamically initialized by
values provided by the users at the run time.
 The parameterized constructor is used for the dynamic
initialization of object at run time.
 Ex:
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point()
{
x=0;
y=0;
}
C++ lecture notes by Hansa Halai
point(int x1,int y1)
{
x=x1;
y=y1;
}
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2,p3;
cout<<"Enter x1 co-ordinate:";
int m,n;
cin>>m;
cout<<"Enter y1 co-ordinate:";
cin>>n;
p1=point(m,n);
C++ lecture notes by Hansa Halai
cout<<"Enter x2 co-ordinate:";
cin>>m;
cout<<"Enter y2 co-ordinate:";
cin>>n;
p2=point(m,n);
cout<<"Enter x3 co-ordinate:";
cin>>m;
cout<<"Enter y3 co-ordinate:";
cin>>n;
p3=point(m,n);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
cout<<"point P3 is = ";
p3.put_point();
return 0;
}
C++ lecture notes by Hansa Halai
 Copy constructor is used to create the new object with
previously created object.
 In other term, copy constructor create a new object as copy
of previous object.
 For example if we create p1 object for point class like,
point p1(5,5) ;
 The following statement create p2 with value of p1.
point p2(p1);
 The copy of constructor for any class is written as:
 Syntax: class_name(class_name& object)
{
// constructor body
}
C++ lecture notes by Hansa Halai
 For ex:
point(point& p) // copy constructor
{
x=p.x;
Y=p.y;
}
 Observe that constructor has one argument which is
reference to the object of same class of which the copy
constructor is member. Using this reference, it copies
each data member.
 We can call copy constructor in either ways
point p2(p1);
or
point p2=p1;
C++ lecture notes by Hansa Halai
#include<iostream>
using namespace std;
class point{
int x,y;
public:
point()
{
x=0;
y=0;
}
point(int x1,int y1)
{
x=x1;
y=y1;
}
point(point& p)
{
x=p.x;
y=p.y;
}
C++ lecture notes by Hansa Halai
void put_point()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
};
int main()
{
point p1,p2(1,1);
cout<<"point P1 is = ";
p1.put_point();
cout<<"point P2 is = ";
p2.put_point();
point p3(p2);
cout<<"point P3 is = ";
p3.put_point();
point p4(p1);
cout<<"point P4 is = ";
p4.put_point();
return 0;
}
C++ lecture notes by Hansa Halai
 The constructor can also be used to allocate memory while
creating objects.
 This will enable the system to allocate the right amount of
memory for each objects when the objects are not of the
same size, thus resulting is the saving memory.
 Allocation of memory to object at the time of their
constructor is called dynamic constructor.
 The memory is allocated with help of new operator.
 By using new operator we get exact amount of memory
storage space at run time which are used in constructor.
C++ lecture notes by Hansa Halai
C++ lecture notes by Hansa Halai
#include<iostream>
#include<string.h>
using namespace std;
class String
{
char *name;
int length;
public:
String()
{
length=0;
name= new char[length+1];
}
String(char *s)
{
length=strlen(s);
name=new char[length+1];
strcpy(name,s);
}
C++ lecture notes by Hansa Halai
void display()
{
cout<<name<<"n";
}
};
int main()
{
char *str="Welcome";
String str1(str),str2("BCA");
String str3(str),str4;
str1.display();
str2.display();
str3.display();
return 0;
}
#include<iostream>
using namespace std;
class matrix
{
int **p;
int d1,d2;
public:
matrix(int x,int y);
void get_element(int i,int j,int val)
{
p[i][j]=val;
}
int &put_element(int i,int j)
{
return p[i][j];
}
};
C++ lecture notes by Hansa Halai
matrix:: matrix(int x, int y)
{
d1=x;
d2=y;
p= new int *[d1];
for(int i=0;i<d1;i++)
{
p[i]=new int[d2];
}
}
int main()
{
int m,n;
cout<<"Enter size of matrix: ";
cin>>m>>n;
matrix A(m,n);
cout<<"Enter matrix Element: ";
int i,j,val;
C++ lecture notes by Hansa Halai
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
cin>>val;
A.get_element(i,j,val);
}
cout<<"n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<" "<<A.put_element(i,j)<<" ";
}
cout<<"n";
}
cout<<"n";
cout<<"The value of on position(1,2) is : "<<A.put_element(1,2);
cout<<"n";
return 0;
} C++ lecture notes by Hansa Halai
 We may create and use constant object using const
keyword before object declaration.
 For Ex:
const matrix X(m,n); // X is constant
 Any attempt to modify the value of const object will
generate compile-time error.
 A constant object can call only const member
function.
C++ lecture notes by Hansa Halai
 The destructor is used to destroy the object that have been
created by constructor.
 It will destroy the object once the use is over.
 Like constructor, destructor is a member function whose name is
same as class name but it is denoted by tild (~) sign.
 For Ex:
~ test()
{
}
or
~ test()
{
delete p;
}
C++ lecture notes by Hansa Halai
 The destructor destroy everything created by the class
automatically.
 You do not have to put any delete keyword in it, except if
you allocate any memory with new keyword.
 There Is always only one destructor in entire class .
 The objects are destroy in the reverse order of their
creation.
 Characteristics of destructor:
 A destructor never takes any arguments and does not
return any value.
 Destructor is having same name as class preceded by
tild(~) sign.
 It is called automatically when the scope of object is over.
 Default destructor is provided by compiler, if user does not
provide.
C++ lecture notes by Hansa Halai
#include<iostream>
using namespace std;
int count=0;
class test
{
public:
test();
~test();
};
test::test()
{
count++;
cout<<count<<" object is created..n";
}
C++ lecture notes by Hansa Halai
test::~test()
{
cout<<count<<" object is destroyed..n";
count--;
}
int main()
{
cout<<"n";
test a;
{
cout<<"In the inner block n";
test x,y,z;
}
return 0;
}
C++ lecture notes by Hansa Halai
C++ lecture notes by Hansa Halai

Contenu connexe

Tendances

Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 
Friend functions
Friend functions Friend functions
Friend functions
Megha Singh
 

Tendances (20)

Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
C functions
C functionsC functions
C functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
C++ oop
C++ oopC++ oop
C++ oop
 
file handling c++
file handling c++file handling c++
file handling c++
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Friend functions
Friend functions Friend functions
Friend functions
 
constructor and destructor-object oriented programming
constructor and destructor-object oriented programmingconstructor and destructor-object oriented programming
constructor and destructor-object oriented programming
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
C programming
C programmingC programming
C programming
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
sSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptxsSCOPE RESOLUTION OPERATOR.pptx
sSCOPE RESOLUTION OPERATOR.pptx
 

Similaire à constructors and destructors in c++

CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
Niti Arora
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
Jussi Pohjolainen
 
Chapter20 class-example-program
Chapter20 class-example-programChapter20 class-example-program
Chapter20 class-example-program
Deepak Singh
 
constructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsconstructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objects
Kanhaiya Saxena
 

Similaire à constructors and destructors in c++ (20)

CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Class and object C++.pptx
Class and object C++.pptxClass and object C++.pptx
Class and object C++.pptx
 
OOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptxOOP-Lecture-05 (Constructor_Destructor).pptx
OOP-Lecture-05 (Constructor_Destructor).pptx
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Function in C program
Function in C programFunction in C program
Function in C program
 
chapter-9-constructors.pdf
chapter-9-constructors.pdfchapter-9-constructors.pdf
chapter-9-constructors.pdf
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Chapter20 class-example-program
Chapter20 class-example-programChapter20 class-example-program
Chapter20 class-example-program
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
constructors and destructors
constructors and destructorsconstructors and destructors
constructors and destructors
 
constructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objectsconstructor with default arguments and dynamic initialization of objects
constructor with default arguments and dynamic initialization of objects
 
Function in c program
Function in c programFunction in c program
Function in c program
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 

Dernier

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Dernier (20)

Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 

constructors and destructors in c++

  • 1.
  • 2.  we know that the objects are allocated memory per instance basis when they are created. But the question is that who will allocate memory to object at the time of creation?.  The c++ provides solution of these problem is constructor, which enables an object initialize itself when it is created.  For example, if we create object student s1 then the compiler automatically supplies the constructor known as default constructor as follows: student { } C++ lecture notes by Hansa Halai
  • 3.  Characteristic of constructor: › Its name is same as class name. › It has no arguments › Its does not have any return type. › Body part is null(no statement in body). › It is called automatically when object is created. › They should be declare in public section. C++ lecture notes by Hansa Halai
  • 4.  Default constructor is constructor that takes no arguments. The default constructor for class student has form student::student().  A constructor which has all default arguments, for example student::student( int x=0) is also default constructor, since it can be called with no argument.  Ex: #include<iostream> using namespace std; class point{ int x,y; public: point() //default constructor { } void set_point() { x=0; y=0; } C++ lecture notes by Hansa Halai
  • 5. void set_point(int x1,int y1) { x=x1; y=y1; } void put_point() { cout<<"("<<x<<","<<y<<")"<<endl; } }; int main() { point p1,p2; p1.set_point(); p2.set_point(1,2); cout<<"point P1 is = "; p1.put_point(); cout<<"point P1 is = "; p2.put_point(); return 0; } C++ lecture notes by Hansa Halai
  • 6.  In above program, we have written default constructor that is exactly same as the compiler provide.  We can write initialization statement in body part of default constructor which is allowed.  For that constructor first create the object by allocating memory and then execute statements in body of constructor, if provided.  If we provide the initialization statements in body of constructor, the object gets initialized by default values provided in body at the time of creating object as constructor.  for Ex: point() // default constructor with initialization { X=0; Y=0; } C++ lecture notes by Hansa Halai
  • 7.  The default constructor are used initialize the object with default values.  But all objects are not initialized to same values rather different object needs to be initialized by different values.  To initialize object with different values, we use function like getvalue().  C++ provide feature is parameterize constructor to solve this problem.  The constructor that can take arguments are called parameterize constructor .  The advantage of using parameterize constructor that we can pass the value at the time of defining object with which the compiler automatically calls it C++ lecture notes by Hansa Halai
  • 8. C++ lecture notes by Hansa Halai #include<iostream> using namespace std; class point{ int x,y; public: point() // default constructor { x=0; y=0; } point(int x1,int y1) // parameterize constructor { x=x1; y=y1; }
  • 9. void put_point() { cout<<"("<<x<<","<<y<<")"<<endl; } }; int main() { point p1,p2(3,9); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is = "; p2.put_point(); return 0; } C++ lecture notes by Hansa Halai
  • 10.  In a class if we use more than one constructor with each constructor are different, this concept is called constructor overloading.  Ex: C++ lecture notes by Hansa Halai #include<iostream> using namespace std; class point{ int x,y; public: point() //default constructor { x=0; y=0; }
  • 11. point(int x1) //one parameter constructor { x=x1; y=0; } point(int x1,int y1) //two parameter constructor { x=x1; y=y1; } void put_point() { cout<<"("<<x<<","<<y<<")"<<endl; } }; C++ lecture notes by Hansa Halai
  • 12. int main() { point p1,p2(3),p3(3,4); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is = "; p2.put_point(); cout<<"point P3 is = "; p3.put_point(); return 0; } C++ lecture notes by Hansa Halai
  • 13.  A argument is a value given in the declaration that the compiler automatically insert if you don’t provide a value in function call.  It is possible to define constructor with default argument.  Ex: #include<iostream> using namespace std; class point{ int x,y; public: point() { x=0; y=0; } C++ lecture notes by Hansa Halai
  • 14. point(int x1,int y1=1) { x=x1; y=y1; } void put_point() { cout<<"("<<x<<","<<y<<")"<<endl; } }; int main() { point p1,p2(3),p3(9); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is = "; p2.put_point(); cout<<"point P3 is = "; p3.put_point(); return 0; } C++ lecture notes by Hansa Halai
  • 15.  As variable , object can be also dynamically initialized by values provided by the users at the run time.  The parameterized constructor is used for the dynamic initialization of object at run time.  Ex: #include<iostream> using namespace std; class point{ int x,y; public: point() { x=0; y=0; } C++ lecture notes by Hansa Halai
  • 16. point(int x1,int y1) { x=x1; y=y1; } void put_point() { cout<<"("<<x<<","<<y<<")"<<endl; } }; int main() { point p1,p2,p3; cout<<"Enter x1 co-ordinate:"; int m,n; cin>>m; cout<<"Enter y1 co-ordinate:"; cin>>n; p1=point(m,n); C++ lecture notes by Hansa Halai
  • 17. cout<<"Enter x2 co-ordinate:"; cin>>m; cout<<"Enter y2 co-ordinate:"; cin>>n; p2=point(m,n); cout<<"Enter x3 co-ordinate:"; cin>>m; cout<<"Enter y3 co-ordinate:"; cin>>n; p3=point(m,n); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is = "; p2.put_point(); cout<<"point P3 is = "; p3.put_point(); return 0; } C++ lecture notes by Hansa Halai
  • 18.  Copy constructor is used to create the new object with previously created object.  In other term, copy constructor create a new object as copy of previous object.  For example if we create p1 object for point class like, point p1(5,5) ;  The following statement create p2 with value of p1. point p2(p1);  The copy of constructor for any class is written as:  Syntax: class_name(class_name& object) { // constructor body } C++ lecture notes by Hansa Halai
  • 19.  For ex: point(point& p) // copy constructor { x=p.x; Y=p.y; }  Observe that constructor has one argument which is reference to the object of same class of which the copy constructor is member. Using this reference, it copies each data member.  We can call copy constructor in either ways point p2(p1); or point p2=p1; C++ lecture notes by Hansa Halai
  • 20. #include<iostream> using namespace std; class point{ int x,y; public: point() { x=0; y=0; } point(int x1,int y1) { x=x1; y=y1; } point(point& p) { x=p.x; y=p.y; } C++ lecture notes by Hansa Halai
  • 21. void put_point() { cout<<"("<<x<<","<<y<<")"<<endl; } }; int main() { point p1,p2(1,1); cout<<"point P1 is = "; p1.put_point(); cout<<"point P2 is = "; p2.put_point(); point p3(p2); cout<<"point P3 is = "; p3.put_point(); point p4(p1); cout<<"point P4 is = "; p4.put_point(); return 0; } C++ lecture notes by Hansa Halai
  • 22.  The constructor can also be used to allocate memory while creating objects.  This will enable the system to allocate the right amount of memory for each objects when the objects are not of the same size, thus resulting is the saving memory.  Allocation of memory to object at the time of their constructor is called dynamic constructor.  The memory is allocated with help of new operator.  By using new operator we get exact amount of memory storage space at run time which are used in constructor. C++ lecture notes by Hansa Halai
  • 23. C++ lecture notes by Hansa Halai #include<iostream> #include<string.h> using namespace std; class String { char *name; int length; public: String() { length=0; name= new char[length+1]; } String(char *s) { length=strlen(s); name=new char[length+1]; strcpy(name,s); }
  • 24. C++ lecture notes by Hansa Halai void display() { cout<<name<<"n"; } }; int main() { char *str="Welcome"; String str1(str),str2("BCA"); String str3(str),str4; str1.display(); str2.display(); str3.display(); return 0; }
  • 25. #include<iostream> using namespace std; class matrix { int **p; int d1,d2; public: matrix(int x,int y); void get_element(int i,int j,int val) { p[i][j]=val; } int &put_element(int i,int j) { return p[i][j]; } }; C++ lecture notes by Hansa Halai
  • 26. matrix:: matrix(int x, int y) { d1=x; d2=y; p= new int *[d1]; for(int i=0;i<d1;i++) { p[i]=new int[d2]; } } int main() { int m,n; cout<<"Enter size of matrix: "; cin>>m>>n; matrix A(m,n); cout<<"Enter matrix Element: "; int i,j,val; C++ lecture notes by Hansa Halai
  • 28.  We may create and use constant object using const keyword before object declaration.  For Ex: const matrix X(m,n); // X is constant  Any attempt to modify the value of const object will generate compile-time error.  A constant object can call only const member function. C++ lecture notes by Hansa Halai
  • 29.  The destructor is used to destroy the object that have been created by constructor.  It will destroy the object once the use is over.  Like constructor, destructor is a member function whose name is same as class name but it is denoted by tild (~) sign.  For Ex: ~ test() { } or ~ test() { delete p; } C++ lecture notes by Hansa Halai
  • 30.  The destructor destroy everything created by the class automatically.  You do not have to put any delete keyword in it, except if you allocate any memory with new keyword.  There Is always only one destructor in entire class .  The objects are destroy in the reverse order of their creation.  Characteristics of destructor:  A destructor never takes any arguments and does not return any value.  Destructor is having same name as class preceded by tild(~) sign.  It is called automatically when the scope of object is over.  Default destructor is provided by compiler, if user does not provide. C++ lecture notes by Hansa Halai
  • 31. #include<iostream> using namespace std; int count=0; class test { public: test(); ~test(); }; test::test() { count++; cout<<count<<" object is created..n"; } C++ lecture notes by Hansa Halai
  • 32. test::~test() { cout<<count<<" object is destroyed..n"; count--; } int main() { cout<<"n"; test a; { cout<<"In the inner block n"; test x,y,z; } return 0; } C++ lecture notes by Hansa Halai
  • 33. C++ lecture notes by Hansa Halai