SlideShare a Scribd company logo
1 of 21
Constructors & Destructors
Review
CS 308 – Data Structures
What is a constructor?
• It is a member function which initializes a
class.
• A constructor has:
(i) the same name as the class itself
(ii) no return type
class rectangle {
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
};
rectangle::rectangle(float h, float w)
{
height = h;
width = w;
xpos = 0;
ypos = 0;
}
Comments on constructors
• A constructor is called automatically whenever a
new instance of a class is created.
• You must supply the arguments to the constructor
when a new instance is created.
• If you do not specify a constructor, the compiler
generates a default constructor for you (expects no
parameters and has an empty body).
void main()
{
rectangle rc(3.0, 2.0);
rc.posn(100, 100);
rc.draw();
rc.move(50, 50);
rc.draw();
}
• Warning: attempting to initialize a data member of
a class explicitly in the class definition is a syntax
error.
Comments on constructors (cont.)
Overloading constructors
• You can have more than one constructor in a class,
as long as each has a different list of arguments.
class rectangle {
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
rectangle(); // another constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
};
Overloading constructors (cont.)
rectangle::rectangle()
{
height = 10;
width = 10;
xpos = 0;
ypos = 0;
}
void main()
{
rectangle rc1(3.0, 2.0);
rectangle rc2();
rc1.draw();
rc2.draw();
}
Composition: objects as
members of classes
• A class may have objects of other classes as
members.
class properties {
private:
int color;
int line;
public:
properties(int, int); // constructor
};
properties::properties(int c, int l)
{
color = c;
line = l;
}
class rectangle {
private:
float height;
float width;
int xpos;
int ypos;
properties pr; // another object
public:
rectangle(float, float, int, int ); // constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
};
Composition: objects as
members of classes (cont.)
Composition: objects as
members of classes (cont.)
rectangle::rectangle(float h, float w, int c, int l):pr(c, l)
{
height = h;
width = w;
xpos = 0;
ypos = 0;
};
void main()
{
rectangle rc(3.0, 2.0, 1, 3);
C++ statements;
}
What is a destructor?
• It is a member function which deletes an object.
• A destructor function is called automatically when
the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing temporary variables ends
(4) a delete operator is called
• A destructor has:
(i) the same name as the class but is preceded by a tilde (~)
(ii) no arguments and return no values
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
};
string::string(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}
string::~string()
{
delete []s;
}
Comments on destructors
• If you do not specify a destructor, the
compiler generates a default destructor for
you.
• When a class contains a pointer to memory
you allocate, it is your responsibility to
release the memory before the class
instance is destroyed.
What is a copy constructor?
• It is a member function which initializes an
object using another object of the same
class.
• A copy constructor has the following
general function prototype:
class_name (const class_name&);
class rectangle {
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
rectangle(const rectangle&); // copy constructor
void draw(); // draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
};
rectangle::rectangle(const rectangle& old_rc)
{
height = old_rc.height;
width = old_rc.width;
xpos = old_rc.xpos;
ypos = old_rc.ypos;
}
void main()
{
rectangle rc1(3.0, 2.0); // use constructor
rectangle rc2(rc1); // use copy constructor
rectangle rc3 = rc1; // alternative syntax for
// copy constructor
C++ statements;
}
Defining copy constructors is
very important
• In the absence of a copy constructor, the
C++ compiler builds a default copy
constructor for each class which is doing a
memberwise copy between objects.
• Default copy constructors work fine unless
the class contains pointer data members ...
why???
#include <iostream.h>
#include <string.h>
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
void print();
void copy(char *);
};
void string::print()
{
cout << s << endl;
}
void string::copy(char *c)
{
strcpy(s, c);
}
void main()
{
string str1("George");
string str2 = str1; // default copy constructor
str1.print(); // what is printed ?
str2.print();
str2.copy("Mary");
str1.print(); // what is printed now ?
str2.print();
}
Defining a copy constructor for the
above example:
class string {
private:
char *s;
int size;
public:
string(char *); // constructor
~string(); // destructor
string(const string&); // copy constructor
void print();
void copy(char *);
};
string::string(const string& old_str)
{
size = old_str.size;
s = new char[size+1];
strcpy(s,old_str.s);
}
void main()
{
string str1("George");
string str2 = str1;
str1.print(); // what is printed ?
str2.print();
str2.copy("Mary");
str1.print(); // what is printed now ?
str2.print();
}
Note: same results can be obtained by overloading the assignment
operator.

More Related Content

Similar to ReviewConstructorDestructorof cplusplus.ppt

Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++Jay Patel
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Tutconstructordes
TutconstructordesTutconstructordes
TutconstructordesNiti Arora
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxAshrithaRokkam
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)ProCharm
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
I am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdfI am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdffortmdu
 
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.pptxAnantjain234527
 

Similar to ReviewConstructorDestructorof cplusplus.ppt (20)

Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Constructor in c++
Constructor in c++Constructor in c++
Constructor in c++
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Bc0037
Bc0037Bc0037
Bc0037
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Tutconstructordes
TutconstructordesTutconstructordes
Tutconstructordes
 
Object and class
Object and classObject and class
Object and class
 
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptxconstructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
constructorsfjy5ediykEASFul;IUWORHusi;gfb.pptx
 
C++ process new
C++ process newC++ process new
C++ process new
 
麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)麻省理工C++公开教学课程(二)
麻省理工C++公开教学课程(二)
 
C#2
C#2C#2
C#2
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
I am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdfI am trying to create a program That works with two other programs i.pdf
I am trying to create a program That works with two other programs i.pdf
 
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
 

Recently uploaded

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksMagic Marks
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfsumitt6_25730773
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...HenryBriggs2
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.Kamal Acharya
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...vershagrag
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...jabtakhaidam7
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptxrouholahahmadi9876
 

Recently uploaded (20)

Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
💚Trustworthy Call Girls Pune Call Girls Service Just Call 🍑👄6378878445 🍑👄 Top...
 
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
Jaipur ❤CALL GIRL 0000000000❤CALL GIRLS IN Jaipur ESCORT SERVICE❤CALL GIRL IN...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 

ReviewConstructorDestructorof cplusplus.ppt

  • 1. Constructors & Destructors Review CS 308 – Data Structures
  • 2. What is a constructor? • It is a member function which initializes a class. • A constructor has: (i) the same name as the class itself (ii) no return type
  • 3. class rectangle { private: float height; float width; int xpos; int ypos; public: rectangle(float, float); // constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function }; rectangle::rectangle(float h, float w) { height = h; width = w; xpos = 0; ypos = 0; }
  • 4. Comments on constructors • A constructor is called automatically whenever a new instance of a class is created. • You must supply the arguments to the constructor when a new instance is created. • If you do not specify a constructor, the compiler generates a default constructor for you (expects no parameters and has an empty body).
  • 5. void main() { rectangle rc(3.0, 2.0); rc.posn(100, 100); rc.draw(); rc.move(50, 50); rc.draw(); } • Warning: attempting to initialize a data member of a class explicitly in the class definition is a syntax error. Comments on constructors (cont.)
  • 6. Overloading constructors • You can have more than one constructor in a class, as long as each has a different list of arguments. class rectangle { private: float height; float width; int xpos; int ypos; public: rectangle(float, float); // constructor rectangle(); // another constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function };
  • 7. Overloading constructors (cont.) rectangle::rectangle() { height = 10; width = 10; xpos = 0; ypos = 0; } void main() { rectangle rc1(3.0, 2.0); rectangle rc2(); rc1.draw(); rc2.draw(); }
  • 8. Composition: objects as members of classes • A class may have objects of other classes as members. class properties { private: int color; int line; public: properties(int, int); // constructor }; properties::properties(int c, int l) { color = c; line = l; }
  • 9. class rectangle { private: float height; float width; int xpos; int ypos; properties pr; // another object public: rectangle(float, float, int, int ); // constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function }; Composition: objects as members of classes (cont.)
  • 10. Composition: objects as members of classes (cont.) rectangle::rectangle(float h, float w, int c, int l):pr(c, l) { height = h; width = w; xpos = 0; ypos = 0; }; void main() { rectangle rc(3.0, 2.0, 1, 3); C++ statements; }
  • 11. What is a destructor? • It is a member function which deletes an object. • A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing temporary variables ends (4) a delete operator is called • A destructor has: (i) the same name as the class but is preceded by a tilde (~) (ii) no arguments and return no values
  • 12. class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor }; string::string(char *c) { size = strlen(c); s = new char[size+1]; strcpy(s,c); } string::~string() { delete []s; }
  • 13. Comments on destructors • If you do not specify a destructor, the compiler generates a default destructor for you. • When a class contains a pointer to memory you allocate, it is your responsibility to release the memory before the class instance is destroyed.
  • 14. What is a copy constructor? • It is a member function which initializes an object using another object of the same class. • A copy constructor has the following general function prototype: class_name (const class_name&);
  • 15. class rectangle { private: float height; float width; int xpos; int ypos; public: rectangle(float, float); // constructor rectangle(const rectangle&); // copy constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function };
  • 16. rectangle::rectangle(const rectangle& old_rc) { height = old_rc.height; width = old_rc.width; xpos = old_rc.xpos; ypos = old_rc.ypos; } void main() { rectangle rc1(3.0, 2.0); // use constructor rectangle rc2(rc1); // use copy constructor rectangle rc3 = rc1; // alternative syntax for // copy constructor C++ statements; }
  • 17. Defining copy constructors is very important • In the absence of a copy constructor, the C++ compiler builds a default copy constructor for each class which is doing a memberwise copy between objects. • Default copy constructors work fine unless the class contains pointer data members ... why???
  • 18. #include <iostream.h> #include <string.h> class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor void print(); void copy(char *); }; void string::print() { cout << s << endl; }
  • 19. void string::copy(char *c) { strcpy(s, c); } void main() { string str1("George"); string str2 = str1; // default copy constructor str1.print(); // what is printed ? str2.print(); str2.copy("Mary"); str1.print(); // what is printed now ? str2.print(); }
  • 20. Defining a copy constructor for the above example: class string { private: char *s; int size; public: string(char *); // constructor ~string(); // destructor string(const string&); // copy constructor void print(); void copy(char *); };
  • 21. string::string(const string& old_str) { size = old_str.size; s = new char[size+1]; strcpy(s,old_str.s); } void main() { string str1("George"); string str2 = str1; str1.print(); // what is printed ? str2.print(); str2.copy("Mary"); str1.print(); // what is printed now ? str2.print(); } Note: same results can be obtained by overloading the assignment operator.