Lab 5 - Classes & Objects Part 3
Lab 5 - Classes & Objects Part 3
1
Table of Contents
• Copy Constructor
• Default Copy Constructor
• User Defined Copy Constructor
• Try it Yourself
2
Copy Constructor
• Default Copy Constructor
• Like any constructor, but it takes another object of the same class as a parameter
• Each class has a default copy constructor.
• Copy constructor can be overloaded.
int main()
• The default copy constructor
class Student { takes an object of the same Class
{ Student s1 = Student();
public: s1.id = 100;
int id; s1.name = "Ahmed";
string name;
}; Student s2 = Student(s1);
// Copy constructor
Student(const Student& s) { • Our copy constructor will initialize
id = s.id; the members of s2 by the values
• The user defined copy constructor of s1 member’s
name = s.name; • The output will be :
takes a const referenced object of
} the same Class • 100
}; • Ahmed 4
TRY IT YOURSELF
5
TRY IT YOURSELF
• Solution
class Rectangle
{
private:
int height, width; int main()
public: {
Rectangle(int height, int width) { Rectangle r1 = Rectangle(10,15);
this->height = height;
this->width= width ; cout << r1.GetHeight() << endl <<
} r1.GetWidth() << endl;
int GetWidth() {
return width;
}
}; 6
THANK YOU