Constructor and Destructor
Constructor and Destructor
Constructor and Destructor
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
Output:
a: 10
b: 20
Parameterized Constructors
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
Parameterized Constructors
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Output
p1.x = 10, p1.y = 15
Copy Constructor
Syntax:
class A
{
A(A &x) // copy constructor.
{
// copyconstructor.
}
}
Copy Constructor
Example:
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
Copy Constructor
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
Output
20
Destructors
Syntax
class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};
Destructors
Example Program
class A
{
// constructor
A()
{
cout << "Constructor called";
}
// destructor
~A()
{
cout << "Destructor called";
}
};
Destructors
int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Output
Constructor called
Constructor called
Destructor called
Destructor called
Destructors
Example Program
#include <iostream>
using namespace std;
class HelloWorld
{
public:
//Constructor
HelloWorld()
{ cout<<"Constructor is called"<<endl; }
//Destructor
~HelloWorld()
{ cout<<"Destructor is called"<<endl; }
//Member function
void display()
{ cout<<"Hello World!"<<endl; } };
Destructors
int main()
{
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}
Output
Constructor is called
Hello World!
Destructor is called