Você está na página 1de 40

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.

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.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 2


Introduction
It is very common for some part of an object to require
initialization before it can beused.
Suppose you are working on 100's of objects and the default
value of a particular data member is needed to bezero.
Initialising all objects manually will be very tedious job.
Instead, you can define a constructor function which initialises
that data member to zero. Then all you have to do is declare
object and constructor will initialise objectautomatically.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 3


Constructor Example
class add When a class contains a
{ constructor, it is guaranteed
int m, n ; that an object created by the
public : class will be initialized
add (); automatically.
}; add a ;
add :: add () Above declaration not only
{ creates the object a of type
m = 0; add, but also initializes its data
n = 0; members m and n to zero.
}
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 4
Constructors
There is no need to write any statement to invoke the constructor
function.
If a ‘normal’ member function is defined for initialization, we
need to invoke that function for each and every objects separately.
Aconstructor that accepts noparameters iscalled the default constructor.
The default constructor for class A will be A : : A ( )

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 5


Characteristics of Constructor
They must be declared in the publicscope.
They are invoked automatically when the objects are created.
They do not have return types, not even void and they
cannot return values.
They cannot be inherited, though a derived class can call the base
class constructor.
Like other C++functions, Constructors can have default
arguments.
Constructors can not be virtual.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 6


Characteristics of Constructor
We can not refer to their addresses.
An object with a constructor (or destructor) can not be used as a
member of a union.
They make ‘implicit calls’ to the operators new and delete when
memory allocation is required.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 7


Constructor
The constructor function is responsible for creation ofobject.
But in previous examples, we have not defined any constructor in
class, so how come the objects were created of thoseclasses?
The answer is, If no constructor is defined in the class in such
situation the compiler implicitly provides a constructor, which is
called asdefault constructor.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 8


Constructor
class sample class sample
{ {
int someDataMember; int someDataMember;
public: public :
void someFunction () sample()
{ {
.. After }
Compilation
.. void someFunction ()
} {
}; ..
..
}
};

Compiler has implicitly added a constructor to the class, which has


empty body, because compiler is not supposed to put any logic in that.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 9


Types of Constructor
Default Constructor/Non-Arg Constructor
Parameterized Constructor
Copy Constructor
Dynamic Constructor

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 10


Default
Constructor
A constructor without any parameter is known as non-arg
constructor or simply default constructor.
If no constructor is defined in a class, then compiler implicitly
provides an empty body constructor which is called as default
constructor.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 11


Non-Arg Constructor Example
class circle In example beside, the
{ constructor function no
float radius;
public: argument, and takes
simply initializes
circle() radius to zero.
{
radius = 0; Non-arg constructor is
} also called as default
}; constructor.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 12


Default Constructor Example
class circle In example beside, we have not
{ defined any constructor, so
float radius;
public: compiler will provide an empty
body constructor to the class,
};
which is called as default
constructor.
class circle
{
float radius;
public:
circle()
{
}
};
Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 13
Parameterised Constructors
Sometimes it becomes necessary to initialize the various data
elements of an objects with different values when they are
created.
This is achieved by passing arguments to the constructor
function when the objects are
created. arguments are called
The constructors that can
take parameterized
constructors.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 14


Parameterised Constructors
class circle
{
float radius; Non-Arg (Default) constructor,
public: which takes no arguments
circle()
{
radius = 0;
}

circle(float r)
{ Parametirised constructor, which
radius = r; takes 1arguments as radius.
}
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 15


Parameterised Constructors
class circle
{
When a constructor is
float radius; parameterized, we must pass the
public: arguments to the constructor
circle()
{ function when an object is
radius = 0; declared.
}
Consider following declaration
circle(float r) circle firstObject;
{ circle secondObject(15);
radius = r;
}
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 16


Two Ways of calling aConstructor
class circle
{
o Implicit call (shorthand method)
float radius; circle ob(7.6);
public:
circle() o Explicit call
{ circle ob;
radius = 0;
} ob = circle(7.6);

circle(float r)
{
radius = r;
}
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 17


Multiple Constructors in aClass
C+ + permits to use more than one constructors in a singleclass.

Add( ) ; / / No arguments

Add (int, int) ; / / Two arguments

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 18


Multiple Constructors in aClass
class add The first constructor receives no
{ arguments.
int m, n;
public :
add ( ) {m = 0 ; n = 0;} The second constructor receives
add (int a, int b) two integer arguments.
{m = a ; n = b ;}
add (add & i) The third constructor receives one
{m = i.m ; n = i.n ;} add object as an argument.
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 19


Multiple Constructors in aClass
class add Add a1;
{ Would automatically invoke the
int m, n; first constructor and set both m
public : and n of a1 to zero.
add ( ) {m = 0 ; n = 0;} Add a2(10,20);
add (int a, int b) Would call the second constructor
{m = a ; n = b ;} which will initialize the data
add (add & i) members m and n of a2 to 10 and
{m = i.m ; n = i.n ;} 20 respectively.
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 20


Multiple Constructors in aClass
class add Add a3(a2);
{ Would invoke the third
int m, n; constructor which copiesthe
public : values of a2 into a3.
add ( ) {m = 0 ; n = 0;} This type of constructor is called
add (int a, int b) the “copy constructor”.
{m = a ; n = b ;} Construction Overloading
add (add & i) More than one constructor
{m = i.m ; n = i.n ;} function is defined in a class.
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 21


Multiple Constructors in a
Class
class complex complex ( ) { }
{
float x, y;
public : This contains the emptybody and
complex ( ) { } does not do anything.
complex (float a)
{ x =y =a; }
complex (float r, float i) This is used to create objects
{ x =r ; y =i } without any initial values.
------
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 22


Multiple Constructors in aClass
C++ compiler has an implicit constructor which creates
objects, even though it was not defined in the class.
This works well as long as we do not use any other constructor in the
class.
However, once we define a constructor, we must also define the
“do-nothing” implicit constructor.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 23


Constructor Overloading
/*.....A program to highlight the concept of constructor
overloading.......... */

#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; }
};

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 25


Constructor Overloading
int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display();
return 0;
} //end of program

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 26


Constructors with DefaultArguments
It is possible to define constructors with default
arguments.
Consider complex (float real, float imag = 0);
The default value of the argument imag is zero.
complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to
imag.
complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 27


Dynamic Initialization of Objects
Providing initial value to objects at run
time.
Advantage – We can provide various initialization
formats, using overloaded constructors.

This provides the flexibility of using


different format of data at run time
depending upon the situation.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 29


Copy Constructor
Acopy constructor is used to declare and initialize an object
from another object.

integer (integer & i);


integer I 2 ( I 1) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is known as
copy initialization.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 30


Copy Constructor
The statement
I 2 = I 1;
will not invoke the copyconstructor.

If I 1 and I 2 are objects, thisstatement is legal and assigns the


values of I 1 to I2, member-by-member.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 31


Copy Constructor
A reference variable has been used as an argument to the copy
constructor.

We cannot pass the argument by value to a copy constructor.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 32


Example
#include<iostream>
using namespace std;

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; }

int getX() { return x; }


int getY() { return y; }
};
Example
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

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.

This will enable the system to allocate the right amount of


memory for each object when the objects are not of the same
size.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 37


Dynamic Constructors
Allocation of memory to objects at the time of their
construction is known as dynamic construction of objects.

The memory is created with the help of the new operator.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 38


Destructors
A destructor is used to destroy the objects that havebeen
created by a constructor.

Like constructor, the destructor is a member function whose


name is the same as the class name but is preceded by atilde.
eg: ~ integer ( ) { }

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 39


Destructors
A destructor never takes any argument nor does it return any
value.

It will be invoked implicitly by the compiler upon exit from the


program – or block or function as the case may be – to clean
up storage that is no longer accessible.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 40


Destructors
It is a good practice to declare destructors ina program since it
releases memory space for further use.

Whenever new is used toallocate memory in the constructor,


we should use delete to free that memory.

Rising Technologies, Jalna (MH). + 91 9423156065, http://www.RisingTechnologies.in 41

Você também pode gostar