31

Constructors and Destructors

Embed Size (px)

Citation preview

Page 1: Constructors and Destructors
Page 2: Constructors and Destructors

NEED OF CONSTRUCTORS Initialization of data members of the class

◦ Define member function (init()) inside class to provide initial values:-

class student

{

private:

int rollno;

float marks;

public:

void init()

{

rollno=0;

marks=0.0;

}

……

};

void main()

{

Student senior;

seniot.init()

}

Using init() function explicitly in order to provide initial values.

Responsibility of initialization solely depends on programmer

Page 3: Constructors and Destructors

CONSTRUCTORS C++ provides a special member function

called the constructor which enables anobject to initialize itself when it is created.This is known as automatic initialization ofobjects.

A constructor is a special memberfunction whose task is to initialize theobjects of its class. It is a special because itsname is the same as the class name. theconstructor is invoked whenever an objectof its associated class is created. It is calledconstructor because it constructs thevalues of data members of the class.

Page 4: Constructors and Destructors

DECLARATION AND DEFINITIONConstructor definition inside a class class student

{

private:

int rollno;

float marks;

public:

student()

{

rollno=0;

marks=0.0;

}

……

};

void main()

{Student senior;

//creates object as well as

intializes data members

}

Constructor definition outside a

class

class student

{

private:

int rollno;

float marks;

public:

//constructor declared

student();

……

};

//constructor defined student:: student()

{

rollno=0;

marks=0.0;

}

Page 5: Constructors and Destructors

DECLARATION AND DEFINITION

Generally, a constructor should be defined

under the public section of a class, so that

its objects can be created in any function.

A class having a no public constructors is a

private class. Only the member function

may declare objects of the class.

Page 6: Constructors and Destructors

CHARACTERISTICS OF

CONSTRUCTOR FUNCTION

They should have the same name as class name.

They should be declared in the public section.

They do not have any return types, not even void and therefore they cannot return any values.

They cannot be inherited, though a derived class can call the base class constructor.

Like other C++ functions they can have default arguments.

Constructor cannot be static

Page 7: Constructors and Destructors

DEFAULT CONSTRUCTOR A constructor that accepts no parameter is

called the default constructor.

With a default constructor, objects arecreated just the same way as variables of otherdata types are created:◦ student s2;

If a class has no explicit constructor defined,the compiler will supply a defaultconstructor.

The default constructor provided by thecompiler does not do anything specific. Itsimply allocates memory to datamembers of objects.

The implicitly – declared default constructor isan inline public members of its class

Page 8: Constructors and Destructors

PARAMETERIZED CONSTRUCTORS

The constructors that can take arguments are called parameterized constructors. (regular constructor)

Declaring a constructor with parameters hides the default constructor

class Test

{

int a;

public:

Test(int i) // constructor with parameter

{

a=i;

}

……….

};

void main()

{

Test ob2(45); // valid

Test ob3; // invalid - no default argument available

}

Page 9: Constructors and Destructors

CALLING PARAMETERIZED CONSTRUCTOR

The constructor can be called in two

ways:-

A. By calling the constructor explicitly

Test obj2=Test(35);

It means that the name of the constructor is explicitly

provided to invoke it, so that the object can be

initialized

B. By calling the constructor implicitly

Test ob3(45);

This method is sometimes called as the shorthand

method.

Page 10: Constructors and Destructors

CALLING PARAMETERIZED

CONSTRUCTOR

Constructors and Primitive Types

//Default constructor used

◦int a,b,c;

//i,j,k initialized with 3,4 and 5

respectively

◦int i(3), j(4), k(5);

◦float x(4.19) , y(3.22);

Page 11: Constructors and Destructors

CLASS WITH CONSTRUCTORS#include<iostream.h>

class integer

{

int m,n;

public:

//constructor declared

integer(int,int);

void display()

{

cout<<“m =“<<m<<endl;

cout<<“n =“<<n<<endl;

}

};

//constructor defined

integer::integer(int x, int y)

{

m=x; n=y;

}

void main()

{

// implicit call

integer i1(0,100);

//explicit call

integer i2=new

integer(25,75)

cout<<“\n

Object1\n”;

i1.display();

cout<<“\n Object1\n”;

i2.display();

}

Page 12: Constructors and Destructors

SIGNIFICANCE OF DEFAULT

CONSTRUCTOR

Default constructor are useful when you

want to create objects without having to

type the initial values.

Array of objects are only possible if class

has a default constructor (implicitly or

explicitly defined)

Page 13: Constructors and Destructors

class Test

{

int a;

char b;

public :

Test(int i, char j)

{

a=i;

b=j;

}

.

};

void main()

{

//error coz default

// constructor not

//available

Test Tarr[5];

//no error

Test obj1(31, „z‟);

…………… }

class Test

{

int a;

char b;

public :

Test(int i, char j)

{

a=i;

b=j;

}

Test( )

{

cout<<“Default\n”;

}

…………

};

void main()

{

Test Tarr[5]; //no error

//no error

Test obj1(31, „z‟);

………………

}

Page 14: Constructors and Destructors

CONSTRUCTORS WITH DEFAULT ARGUMENTS

class A

{

int a,b;

public:

A(int x, int y=10);

A();

};

A::A(int x, int y)

{

a=x; b=y;

}

A::A()

{

a=0;b=0;

}

void main()

{

A obj1(10,100); A obj2;

A obj3(20);

}

class A

{

int a,b;

public:

A(int x=20, int y=10);

A();

};

A::A(int x, int y)

{

a=x; b=y;

}

A::A()

{

a=0;b=0;

}

void main()

{

A obj2; //error ambiguity

}

A constructor with default

arguments is equivalent to a

default constructor.

Page 15: Constructors and Destructors

CONSTRUCTOR OVERLOADINGclass Teacher

{char Subject[30];int Salary;

public:Teacher( ) // Function 1{

strcpy (Subject, “Comp. sci.”);Salary = 15000;

}Teacher ( char T[ ]) // Function 2{

strcpy (Subject, T);Salary = 15000;

}Teacher ( int S) // Function 3{

strcpy (Subject, “Comp. Sci.”);Salary = S;

}Teacher (chat T[ ], int S) // Function 4{

strcpy (Subject, T);Salary = S;

}};

Page 16: Constructors and Destructors

COPY CONSTRUCTOR

A copy constructor is used to declare and

initialize an object from another object.

eg:- Person q(“Mickey”);

Person p=q; //copy constructor

Person r(p); //copy constructor

r=q // assignment operator

The assignment operator is called for an

existing object to which a new value is

being assigned.

Page 17: Constructors and Destructors

COPY CONSTRUCTOR

The process of initialization through a copy

constructor is known as copy

initialization.

A copy constructor takes a reference to an

object of the same class as itself as an

argument.

Syntax:-

class ( class & type)

{

…………

}

Page 18: Constructors and Destructors

class code{

int id;public:

code() { } // default constructor// parameterized constructorcode(int a ) { id=a;}code (code & x) // copy constructor{

id=x.id;}void display(){

cout<<id;}

};void main(){

code A(100); // obj A created and intializedcode B(A); // copy constructor calledcode C=A; // copy constructor called

code D; //obj D created and not intializedD=A; // copy constructor not calledcout<<“\n id of A : “; A.display();cout<<“\n id of B : “; B.display();cout<<“\n id of C : “; C.display(); cout<<“\n id of D : “; D.display();

}

Page 19: Constructors and Destructors

SITUATION WHEN COPY CONSTRUCTOR IS

CALLED

When an object is created from

another object of the same type

When an object is passed by value

as a parameter to a function

When an object is returned from

a function

Page 20: Constructors and Destructors

QUESTION

How many times is the copy constructor called in the following code, using class A:A func(A)

{

A y(x);

A z= y;

return z;

}

void main()

{

A a;

A b=func(a);

A c=func(b);

}

Page 21: Constructors and Destructors

WHY OBJECT PASSED BY

REFERENCE TO COPY

CONSTRUCTOR

When an object is passed by value, its copy

is made.

To make a copy of an object copy

constructor is called. Thus, it calls itself again.

In fact it calls itself over and over again until

compiler goes out of memory.

So, the object is passed by reference which

creates no copy

Page 22: Constructors and Destructors

ORDER OF CONSTRUCTOR

INVOCATION The objects are constructed in the order

they are defined.

◦ Eg:- Sample s1,s2,s3

◦ The order of construction is s1, s2 and s3.

If a class containing objects of another

classes as its members, then the

constructor for member objects are

invoked first and then the constructor for

the containing class is invoked.

Page 23: Constructors and Destructors

class A{

public:A()

{cout<<”Constructor A\n”;}};class B{

public:B()

{cout<<”Constructor B\n”;}};class C{A ob1,ob2;B ob3; public:

C(){cout<<”Constructor C\n”;}

};void main(){

C oc;B ob;A oa;

}

Page 24: Constructors and Destructors

OUTPUT

Constructor A //ob1

Constructor A //ob2

Constructor B //ob3

Constructor C // oc

Constructor B //ob

Constructor A //oa

Page 25: Constructors and Destructors

DYNAMIC INITIALIZATION OF OBJECTS

Class objects can be initialized dynamically

i.e. the initial value of an object may be

provided during run time

Page 26: Constructors and Destructors

class sample

{

int rollno; float marks;

public:

sample(int a float b)

{

rollno=a; marks=b;

}

……. //other members

};

void main()

{

int x; float y;

cout<<“Enter roll no of the student:”;

cin>>x;

cout<<“\n Enter marks of the student:”;

cin>>y;

sample s1(x,y);

}

Page 27: Constructors and Destructors

DESTRUCTORS

A destructor is a member function whose

name is the same as the class name but is

preceded by tilde(~)

~classname()

A destructor takes no arguments, and no

return types can be specified for it.

It is called automatically by the compiler

when an object is destroyed.

A constructor initializes an object and a

destructor deinitializes an object when it is

no longer needed.

Page 28: Constructors and Destructors

NEED FOR DESTRUCTORS

During the construction of an object by

the constructor, resources are allocated

for use e.g., allocation of memory, opening

a file etc. These allocated resources must

be deallocated before the object is

destroyed. A destructor is responsible for

this task and performs all clean-up jobs

like closing a file, deallocating and

releasing memory area automatically.

Page 29: Constructors and Destructors

DECLARATION AND DEFINITION

A destructor should be defined under the

public section of a class, so that its object

can be destroyed in any function.

If more than one object is being

destructed, destructors are invoked in the

reverse order in which the

constructors were called.

Page 30: Constructors and Destructors

IMPLEMENTATION OF DESTRUCTORSint count=0;class alpha{

public:alpha(){

count++;cout<<“\n no of objects created

“<<count;}

~alpha(){

cout<<“\n no of objects destroyed “<<count;

count--; }

};void main(){

cout<<“\n\n Enter Main\n”;alpha a1,a2,a3,a4;{

cout <<“\n\n Enter Block 1\n”;alpha a5 ;

}{cout<<„\n\n Enter Block 2\n”;alpha a6;}

cout<<“\n\nRe-enter main \n‟;

}

Page 31: Constructors and Destructors

OUTPUT Enter Main

◦ No. of objects created 1

◦ No. of objects created 2

◦ No. of objects created 3

◦ No. of objects created 4

Enter Block1◦ No. of objects created 5

◦ No. of objects destroyed 5

Enter block 2 ◦ No. of objects created 5

◦ No. of objects destroyed 5

Re-enter main() No. of objects destroyed 4

No. of objects destroyed 3

No. of objects destroyed 2

No. of objects destroyed 1