Escolar Documentos
Profissional Documentos
Cultura Documentos
in 1
Introduction
A constructor is a special member function whose task is to
initialize the data members of an objects of its class.
It is special because it has same name as its classname.
It invokes automatically whenever a new object of its associated
class is created.
It is called constructor because it constructs the initial values of
data members and build your programmatic object.
circle(float r)
{ Parametirised constructor, which
radius = r; takes 1arguments as radius.
}
};
circle(float r)
{
radius = r;
}
};
Add( ) ; / / No arguments
#include <iostream>
using namespace std;
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; }
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 24
Constructor Overloading
ABC(int a,int b)
//constructor 3 with two argument
{ x = a; y = b; }
void display()
{ cout << "x = " << x << " and " << "y = " << y << endl; }
};
class Point
{
private:
int x, y;
public:
Point(int x1, int y1): x(x1), y(y1) { }
// Copy constructor
Point(const Point &p2) : x (p2.x), y(p2.y) {}
// Point(const Point &p2) {x = p2.x; y = p2.y; }
return 0;
}
Object as an Argument Example
#include <iostream>
using namespace std;
class Demo {
private: int a;
public:
void set(int x) { a = x; }
void sum(Demo ob1, Demo ob2)
{ a = ob1.a + ob2.a; }
void print()
{ cout<<"Value of A : "<<a<<endl; }
};
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 35
Example 2
int main() {
//object declarations
Demo d1; Demo d2; Demo d3;
//assigning values to the data member of
objects
d1.set(10);
d2.set(20);
//passing object d1 and d2
d3.sum(d1,d2);
//printing the values
d1.print(); d2.print(); d3.print();
return 0;
}
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 36
Dynamic Constructors
The constructors can also be used to allocate memory while
creating objects.