Constructors types:
default constructor
parametric constructor
copy constructor
copy constructor vs. overloaded = operator
Compiler supplies below for each class:
default constructor
copy constructor
overloaded = operator
#include <iostream>
using namespace std;
class Point
{
public:
double x, y;
Point()
{
x = 0.0;
y = 0.0;
cout << "Point instance created" << endl;
}
void printPoint ()
{
cout <<"(" <<x <<"," <<y <<")"<<endl;
}
};
int main()
{
Point p;
p.printPoint();
}
#include <iostream>
using namespace std;
class Point
{
public:
double x, y;
Point()
{
x = 10.0;
y = 20.0;
cout << "Point instance created" << endl;
}
Point(double nx, double ny)
{
x = nx;
y = ny;
cout << "2-parameter constructor" << endl;
}
void printPoint ()
{
cout <<"(" <<x <<"," <<y <<")"<<endl;
}
};
int main()
{
Point p(2.0,3.0);
p.printPoint();
}
#include <iostream>
using namespace std;
class Point
{
public:
double x, y;
Point()
{
x = 10.0;
y = 20.0;
cout << "Point instance created" << endl;
}
Point(double nx, double ny)
{
x = nx;
y = ny;
cout << "2-parameter constructor" << endl;
}
void printPoint ()
{
cout <<"(" <<x <<"," <<y <<")"<<endl;
}
};
int main()
{
Point p(2.0,3.0);
Point r = p; //copy constructor
//Point p(2.0,3.0);
//Point r;
//r = p; //overload assignment = operator
r.printPoint();
}
//copy constructor used here
#include <iostream>
using namespace std;
class Point
{
public:
double x, y;
Point()
{
x = 10.0;
y = 20.0;
cout << "default constructor" << endl;
}
Point(double nx, double ny)
{
x = nx;
y = ny;
cout << "2-parameter constructor" << endl;
}
Point(Point &c)
{
x = c.x;
y = c.y;
cout << "copy constructor" << endl;
}
void printPoint ()
{
cout <<"(" <<x <<"," <<y <<")"<<endl;
}
};
int main()
{
Point p(20.0,30.0);
Point r = p; //copy constructor
//Point p(2.0,3.0);
//Point r;
//r = p; //overload assignment = operator
r.printPoint();
}
//overloaded = operator used here
#include <iostream>
using namespace std;
class Point
{
public:
double x, y;
Point()
{
x = 10.0;
y = 20.0;
cout << "default constructor" << endl;
}
Point(double nx, double ny)
{
x = nx;
y = ny;
cout << "2-parameter constructor" << endl;
}
Point(Point &c)
{
x = c.x;
y = c.y;
cout << "copy constructor" << endl;
}
void printPoint ()
{
cout <<"(" <<x <<"," <<y <<")"<<endl;
}
};
int main()
{
//Point p(20.0,30.0);
//Point r = p; //copy constructor
Point p(2.0,3.0);
Point r;
r = p; //overload assignment = operator
r.printPoint();
}
//destructor
#include <iostream>
using namespace std;
class Point
{
public:
int x, y;
Point()
{
x=0.0;
y=0.0;
cout << "constructor invoked" << endl;
}
~Point()
{
cout << "destructor invoked" << endl;
}
void printPoint ()
{
cout <<"(" <<x <<"," <<y <<")"<<endl;
}
};
int main()
{
Point r;
r.printPoint();
return 0;
}