20. When Copy Constructor is called
• When we initialize the object with another
existing object of the same class type. For
example, Student s1 = s2, where Student is
the class.
• When the object of the same class type is
passed by value as an argument.
• When the function returns the object of the
same class type by value.
21. #include<iostream.h> Copy Constructor Example
#include<conio.h>
class A
{
public: int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
} };
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
getch(); }
25. Constructor in C++
• Destructor in C++
• Constructor Overloading
• Constructor Overloading Example
• This Keyword
• Hands on Example
By
Prof. Sandeep Vishwakarma
26.
27. Rules for Destructors
• Destructor is a type of special member function of a
class.
• It is used to destroy the memory allocated by the
constructor.
• It has the same name as the class prefixed with a tilde
(~) sign.
• Destructor does not take any arguments and cannot
return or accept any value.
• It is called automatically by the compiler when the
object goes out of scope.
• Compiler calls the destructor implicitly when the
program execution is exited.
28.
29.
30.
31.
32.
33. Example - 1 Constructor Overloading
class Student
{
public:
int rollno;
string name;
Student(int x) // first constructor
{
rollno = x;
name = "None";
}
34. Student(int x, string str) // second constructor
{
rollno = x;
name = str;
}};
int main()
{
Student A(10);
Student B(11, "John");
getch();
}
35. Example - 2 Constructor Overloading
#include <iostream.h>
#include <conio.h>
class ABC
{
private:
int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument
{
x = y = a;
}
36. ABC(int a, int b) //constructor 3 with two argument
{
x = a;
y = b;
}
void display()
{
cout << "x = " << x << " and " << "y = " << y << endl;
} };
int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display();
getch(); }
37. this Keyword
this is a keyword that refers to the current
instance of the class. There can be 3 main
usage of this keyword in C++.
• It can be used to pass current object as a
parameter to another method.
• It can be used to refer current class
instance variable.
• It can be used to declare indexers.