4 Constructor Destructor
4 Constructor Destructor
Destructor:
destructor is a special member function that cleans
and destroys an object.
Constructor:
•A constructor is a member function that creates
an object when it is called and initializes the
data members of an object when it is executed.
1)Default constructors
2)Parameter constructors
3)Copy constructors
1)Default constructor
~class_name ( )
{
//Some code
}
public:
// Non-default Constructor int main(void) {
point (double px, double py) point a;
{ point b = point(5, 6);
x = px, y = py; b.display();
}
}
Q1-Predict the output??????
include "iostream" void display()
using namespace std; {
cout<<x<<" "<<y;
class point { }
private:
double x, y; };
ERROR
public: !!!
// Non-default Constructor int main(void) {
point (double px, double py) point a;
{ point b = point(5, 6);
x = px, y = py; b.display();
} a.display();
}
Why Its Error??????
class point { };
private:
double x, y; int main(void) {
point b = point(5, 6);
b.display();
public:
// Non-default Constructor }
point (double px, double py) OUTPUT:
{ 5 6
x = px, y = py;
}
void display()
Q2) Predict the Output ?
#include<iostream>
using namespace std;
class Point
{
Point( ) { cout << "Constructor called"; }
};
int main()
{
Point t1;
return 0;
}
Complier Error:
By default all members of a class are private. Since
no access specifier is there for Point(), it becomes
private and it is called outside the class when p1 is
constructed in main.
Q3) Predict the output:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(const Point &p)
{ x = p.x; y = p.y; }
};
int main()
{
Point p1;
Point p2 = p1;
return 0;
}
OUTPUT:
#include <iostream>
using namespace std;
class Point
{
int x, y;
public:
Point(int i, int j) { x = i; y = j; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 20);
Point p2 = p1; // This compiles fine
cout << "x = " << p2.getX() << " y = " << p2.getY();
return 0;
}
OUTPUT:
x = 10 y = 20
Compiler creates a copy constructor if we don’t write our own.
Compiler creates it even if we have written other constructors in class.
Q5) Like constructors, can there be more
than one destructors in a class?
a) Yes
b) No
Answer:
No, there can only one destructor in a class with classname
preceded by ~, no parameters and no return type.
Q6) Predict the output??
#include<iostream.h>
class IndiaBix
{
public: IndiaBix()
a)The program will print the output India.
{
cout<< "India"; b)The program will print the output Bix.
}
c)The program will print the output IndiaBix.
~IndiaBix()
{ d)The program will report compile time erro
cout<< "Bix";
}
};
int main()
{
IndiaBix objBix;
return 0;
}
Answer:
c)The program will print the output IndiaBix.