CPP Language / Constructors and Their Types
It is function of class and is automatically called when object (instance of class) created.
Differences between Constructor and normal functions
Constructor
|
Normal Functions
|
same name as the class name
|
Class name differs from function name.
|
don’t have return type
|
have return type
|
when object created it is automatically called
|
objectname.fuctionname(parameters);
|
If you won’t specify constructor in program C++ compiler generates a default
constructor
|
you
won’t specify function in program C++ compiler won’t generates a default
function
|
Constructors Types
Constructors Types
|
Details
|
Syntax
|
Default
|
Won’t Take parameters
|
Class_name()
|
Parameterized
|
Take parameters
|
Class_name(parameters)
|
Copy
|
Take parameters
|
Class_name(Const Class_name Old_Object )
|
Constructor Type |
Program |
Output |
Default constructor |
#include
using namespace std;
class a {
public:
int b, c;
// Default Constructor
a()
{ b = 10; c = 20; }
};
int main()
{
a aobj;
cout << "b: " << aobj.b << endl << "c: " << aobj.c;
return 1;
}
|
b: 10
c: 20
|
Parameterized Constructors
|
#include
using namespace std;
class a {
private:
int x, y;
public:
// Parameterized Constructor
a(int x1, int y1)
{ x = x1; y = y1; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
a d1(10, 15);
cout << "d1.x = " << d1.getX() << ", d1.y = " << d1.getY();
return 0;
}
|
d1.x = 10, d1.y = 15 |
Copy Constructor |
#include
using namespace std;
class a
{
private: int x, y; //data members
public:
a(int x1, int y1)
{ x = x1; y = y1;}
/* Copy constructor */
a (const a &oldobj)
{ x = oldobj.x; y = oldobj.y; }
void display()
{ cout<
};
int main()
{
a obj1(10, 15);
cout<<"Normal constructor : ";
obj1.display();
a obj2 = obj1;
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
|
Normal constructor : 10 15
Copy constructor : 10 15
|
|