Sunteți pe pagina 1din 31

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
CONSTRUCTORS
C++ provides a special member function
called the constructor which enables an
object to initialize itself when it is created.
This is known as automatic initialization of
objects.
A constructor is a special member
function whose task is to initialize the
objects of its class. It is a special because its
name is the same as the class name. the
constructor is invoked whenever an object
of its associated class is created. It is called
constructor because it constructs the
values of data members of the class.
DECLARATION AND DEFINITION
Constructor 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;
}
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.
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
DEFAULT CONSTRUCTOR
A constructor that accepts no parameter is
called the default constructor.
With a default constructor, objects are
created just the same way as variables of other
data types are created:
student s2;
If a class has no explicit constructor defined,
the compiler will supply a default
constructor.
The default constructor provided by the
compiler does not do anything specific. It
simply allocates memory to data
members of objects.
The implicitly declared default constructor is
an inline public members of its class
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
}
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.
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);
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();
}
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)
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);

}
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.
CONSTRUCTOR OVERLOADING
class 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;
}
};
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.
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)
{

}
class code
{
int id;
public:
code() { } // default constructor
// parameterized constructor
code(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 intialized
code B(A); // copy constructor called
code C=A; // copy constructor called
code D; //obj D created and not intialized
D=A; // copy constructor not called
cout<<\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();
}
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
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);
}
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
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.
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;
}
OUTPUT
Constructor A //ob1
Constructor A //ob2
Constructor B //ob3
Constructor C // oc
Constructor B //ob
Constructor A //oa
DYNAMIC INITIALIZATION OF OBJECTS
Class objects can be initialized dynamically
i.e. the initial value of an object may be
provided during run time
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);
}
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.
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.
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.
IMPLEMENTATION OF DESTRUCTORS
int 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;
}
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

S-ar putea să vă placă și