Sie sind auf Seite 1von 13

[Type text]

CAMBRIDGE SCHOOL,NOIDA

Constructors
-Once

a class is defined, using the class name as data type


specifier, object can be created. After creation of object is over,
the initialization of the data members of that object, with legal
initial values is done, by calling appropriate member function.
However C++ provides a welldefined mechanism, for initializing object
when it is created, by means of Constructor.

A Constructor is a special initialization member function of a


class that is called automatically whenever an instance of a class
(object) is declared. Its job is to allocate memory to the object
and initialize the data members of the object to legal initial
values.
Characteristics of Constructors

A Constructor is a member function that has the same name


as that of the class.
No return data type (not even void) can be specified for a
constructor.
Constructors are special member function of a class, which
are called automatically as soon as an object is created.
Declaration And Definition Of Constructor
A Constructor is a member function with the same name as class
and without the return data type. A constructor is defined like
other member function of a class i.e either as inline or outside of
the class definition.
Example Definition and declaration of Constructor
class student
{
int rollno;
float perc;
public:
student() // constructor
{
rollno = 0;
perc = 0.0;
}
void initdata( ) //Member function to initialize data
members
{
rollno = 0;
perc = 0.0;
Class XII-COMPUTER SCIENCE
1

[Type text]
CAMBRIDGE SCHOOL,NOIDA

}
};
Like any other member function, the constructor can also be defined outside the class
.
class student
{
int rollno;
float perc;
public:
student(); //declaration of constructor function
void initdata( ) //Member function to initialize data members
{
rollno = 0;
perc = 0.0;
}
};
student::student() // constructor definition outside class
{
rollno = 0;
perc = 0.0;
}
Note : A Constructor can be defined in both public and private section of the class
and also follow the usual access rules of a class .
A Constructor, defined in the private section of the class is not available to the
non-member functions and objects of such class can only be created inside
member functions. In such situation no object (of class with private
constructor) can be created outside the class as private constructor cannot be
invoked by non member function and the compiler provided constructor
remains hidden .
A Constructor should be defined under the public section of the class so that
any function can access it to create object.

In the above example, the statement : student s1; will


automatically make a call to the constructor function which will
allocate memory space to the object s1 and initialize its data
members. Without the constructor, the initialization of the data
members to appropriate initial values can only be done, by
making specific call to the member function initdata().
Need for Constructors
A constructor for a class is needed so that compiler automatically initializes the data
member of an object to some legal initial values as soon as it is created. Without a
constructor, a member function (written to initialize the data members) has to be
explicitly called to initialize the data members to their legal initial values. In case, the
programmer fails to invoke that function, the object will be full of garbage and the
program might give incorrect result.

Default Constructor

Class XII-COMPUTER SCIENCE


2

[Type text]
CAMBRIDGE SCHOOL,NOIDA

A Constructor, which accepts no parameter is called Default


Constructor. In the previous example the constructor
student::student() is an example of default constructor.
If the user defined class does not contain an explicit constructor,
compiler supplies one in-built default constructor to construct
the object. This compiler provided in-built default
constructor only allocates memory to the object, but does
not initialize the data members to any valid values i.e after
memory allocation it assigns arbitrary values to the data
members. Because of that without a constructor, a member
function (like initdata()) has to be explicitly called to initialize
the data members to their legal initial values.
Once the programmer defines his own constructor in the
class, the default constructor provided by the compiler
becomes deactivated.
Parameterized Constructor :

The Constructor, which can take arguments is called


Parameterized Constructor. This type of constructor gives the
user an opportunity to create various objects with different
initial values. This is achieved by passing different data items as
argument which are passed as arguments to the constructor
function when an object is created.
Example: Creation of parameterized constructor
class student
{
int rollno;
float perc;
public:
student(int rno,float p) // parameterized constructor
{
rollno = rno;
perc = p;
}
void showdata( ) //Member function to display data
members
{
cout<<Roll no <<rollno;<<\tPercentage =
<<perc;
}
Class XII-COMPUTER SCIENCE
3

[Type text]
CAMBRIDGE SCHOOL,NOIDA

}; //end of class definition


With parameterized constructor, one must provide initial values as arguments, at the
time of creating an object, otherwise compiler will report an error .
There are two ways of making a call to a Parameterized constructor
Implicit call
Explicit call
Implicit Call To The Constructor

By Implicit call, it means that the parameterized constructor is


invoked automatically at the time of object creation. For
example, to create an object of student type with initial values
2and 75.5(as (rollno and perc), the constructor will be called
implicitly as follows :
student s1(2,75.5); //implicit call
Explicit Call To The Constructor
In this method, the name of the constructor is explicitly
provided to invoke the constructor so that object can be
initialized .
For example to create the above given object s1 by explicit call,
the statement should be : student s1 = student(2,75.5);
In the following example another object s2 is created by explicit
call to constructor, by passing variable as parameter.
Example :

int r; float p; cin>> r>>p;


student s2=student(r,p);

Therefore, argument values may be passed to a parameterized constructor either by


calling implicitly or explicitly.

Temporary instance
A temporary instance is an object of a class, that is accessible in
the memory as long as it is being used or referenced, and after
this it becomes inaccessible. Temporary instance does not have
any name. Explicit constructor call lets you to create a
temporary instance. For example: student(3,89.7).showdata( );
In the above example, student(3,89.7) is an anonymous
temporary object and accessible as long as the function
showdata( ) is executing it. After that it becomes inaccessible.
It is also possible to create an object, by passing one of the two
parameters into the constructor and initialize the other in the
constructor itself.
Example : class student
{
int rollno;
float perc;
Class XII-COMPUTER SCIENCE
4

[Type text]
CAMBRIDGE SCHOOL,NOIDA

public:
student(float p) // parameterized constructor
{
rollno = 0;
perc = p;
}
:
:
} // End of class
void main()
{
student s1(89.3); //s1 objects rollno = 0 and perc = 89.3
:
}
Multiple Constructors In A Class
C++ allows use of more than one constructor in the class. In that situation, depending
on the object creation statement, a particular constructor function is activated. In the
following example, there are three constructors in the class student. The first, which
takes no argument, is used to create objects, which are initialized to 0. The second,
which takes one argument, is used to create objects and initialize them and the third
constructor, which takes two arguments, is also used to create objects and initialize
them to specific values. When more than one constructor function is defined in a
class, it is called Constructor function Overloading. Constructor overloading is a
method to implement Polymorphism feature of OOP.
Example : Program having multiple Constructors
class student
{
int rollno;
float perc;
public:
student() // Constructor 1
{
rollno = 0;
perc = 0.0;
}
student(float p) // Constructor 2
{
rollno = 0;
perc = p;
}
student(int rno,float p) // Constructor 3
{
rollno = rno;
perc = p;
}
:
}; //end of class definition
Class XII-COMPUTER SCIENCE
5

[Type text]
CAMBRIDGE SCHOOL,NOIDA

void main()
{
student s1;
// call to the constructor 1. Now s1s rollno=0 ,perc=0.0
student s2(99.3); //call to the constructor 2. s2s rollno=0 ,perc=99.3
student s2(3,99.3);//call to the constructor 3. S3s rollno=3 ,perc=99.3
:
}

Constructor with default arguments


Similar to normal function, it is possible to define Constructor
with arguments having default values, so that at the time of
object creation, if no data items are passed into the constructor,
then the data members of the object will be initialized to the
specified default values.
Example:
class student
{
int rollno;
float perc;
public:
student(int rno=1,float p=40) // parameterized constructor
{
rollno = rno;
perc = p;
}
:
};//end of class definition
void main()
{
student s1;
// Call to the constructor without parameter rollno and
//perc will have default values 1 and 40
student s2(3); //Call to the constructor with one parameter. Rollno will
//be = 3 and perc will have the default value 40
student s3(4,99.3); //Call to the constructor with two parameters. Now
// rollno=4,perc=99.3
:
}

Constructor with default arguments is said to be equivalent to


the default constructor. It is because, a constructor with default
argument values, allows creation of object without any data item
provided as parameter to the constructor (in the above example
object s1), just the same way as a default constructor allows you
to do.
Note: No other constructor should be defined along with the
constructor with default arguments, since it would confuse the
Class XII-COMPUTER SCIENCE
6

[Type text]
CAMBRIDGE SCHOOL,NOIDA

compiler as to which constructor to call as constructor with


default arguments is called in all cases.
Copy Constructor
A copy constructor is a constructor that can be used to initialize one object with the
values of another existing object of the same class during declaration, i.e. the values
of all the data members of the existing object are copied to the data members of the
newly created object.
Example: Using Copy constructor
class student
{
int rollno;
float perc;
public:
student(int rno,float p) // parameterized constructor
{
rollno = rno;
perc = p;
}
};
void main()
{
student st1(2,78.5); //parameterized constructor initialize st1.
student st2 = st1; // st1 copied into st2,copy constructor called
student st3 (st2); // another way to invoke a copy constructor
//st2 copied into st3
:
}
A copy constructor is invoked when one object is defined and initialized with another
object of same class. The process of initializing an object through a copy constructor
is known as copy initialization.
The given assignment statement:student st4;
st4=st2;
will not invoke copy constructor. This statement is assigning the data members of st2
to st4.
When a Copy Constructor is called ?
The copy constructor is invoked automatically by the compiler in the following
situations.
When an object is defined and its data members are initialized by the data
members of an existing object.
student s1(1,98.5);//parameterized constructor is invoked
student s2=s1; //copy constructor is invoked
The Copy Constructor is invoked when an object is passed into a function by
value method. When an object is passed into a function by value a copy of the
object (passed as parameter) is made in the called function, hence copy
constructor is invoked.
Example :
void report(student temp)
//report() taking object as parameter
{
:
:
Class XII-COMPUTER SCIENCE
7

[Type text]
CAMBRIDGE SCHOOL,NOIDA

}
void main()
{
student st1(2,75.5);
report(st1);//function call
}
In the above example, as soon as the call to the function report (..) is made,
copy constructor will be invoked to copy the object st1 passed as parameter to
another newly created object temp.
-

When an object is returned by a function the copy constructor is invoked. For


example
student st4=newfunc();//object is returned
Here the copy constructor will create a temporary object to hold the value
returned by the function newfunc() and then this temporary object will be
assigned to object st4.

User defined Copy Constructor


Although, C++ compiler has its in-built copy constructor, the programmer can also
define his own copy constructor in the program. The user defined Copy Constructor is
defined in the class as a parameterized constructor receiving reference to an object of
the same class as parameter. The reference of the object (the existing one) is passed
using address operator(&) into the constructor function. The following example
defines a copy constructor using the class student defined in the previous example.
class student
{
int rollno;
float perc;
public:
student(int rno,float p) // parameterized constructor
{
rollno = rno;
perc = p;
}
student(student &st); //prototype of copy constructor
:
};//End of class definition
student::student(student &st) //definition of copy constructor
{
rollno=st.rollno;
perc=st.perc;
}
void main()
{
student stud1(2,78.5); //parameterized constructor initialize stud1.
student stud2(stud1); // call to Copy constructor
:
}
In the above given example, object stud1 is created and initialized by invoking the
parameterized constructor. Another object stud2, is created as a copy of stud1 with the
help of an user defined copy constructor. As parameter, the reference of the existing
object stud1 is passed into the constructor function and a data member-wise copy of
stud1as stud2 is made.
Note :
Class XII-COMPUTER SCIENCE
8

[Type text]
CAMBRIDGE SCHOOL,NOIDA

While defining a copy constructor, the argument of the copy constructor


function (i.e. the existing object) has to be passed by reference method, not by
value method. When an object is passed into any function by value method, then a
copy of the object is made in the function called and therefore a copy constructor will
be invoked. But as in this case the copy constructor is creating a copy of the object for
itself, thus it calls itself again. Hence passing an object by value into a copy
constructor function would result in copy constructor calling itself, on and on
indefinitely resulting in an out of memory error.
Destructors
A destructor is used to destroy the objects that have been created by constructor. A
destructor is called automatically by the compiler, when an object ceases to exist and
by that release memory space. For a local and non-static object, the destructor is
called, just before the control is coming back from the function in which the object is
defined. For static and global objects the destructor is called before the program
terminates. Even when a program is terminated using an exit() function, the destructor
is called for the objects which exists at that time.
Declaration And Definition Of User Defined Destructor
A destructor is also a member function whose name is same as the class name but is
preceded by a tilt (~). When user does not define his own destructor, compiler
generates a default destructor. The destructor is executed automatically when an the
control reaches at the end of class scope
The following points should be kept in mind while defining and writing an user
defined destructor
The destructor is a member function of a class which has the same name as
that of a class , prefixed by a tilt (~).
The Destructor cannot have arguments
It has no return type, not even void.
A destructor should be defined in the public section of the class and by that its
objects destroyed by any function. Otherwise when a private destructor
function is defined, it becomes available only to the member functions and
hence its object cannot be destroyed by non-member function.
Example:
class sample
{
int a,b;
public:
sample(int x,int y) //constructor
{
a=x;
b=y;
}
~sample() //destructor function
{
cout<<"destructing object;
}
};//end of class
void main()
{
sample s1(2,3);
sample s2(5,7);
:
}
Class XII-COMPUTER SCIENCE
9

[Type text]
CAMBRIDGE SCHOOL,NOIDA

When control will come out of main(), the objects s1 and s2 will be destroyed and
each time the destructor function is destroying any object, it will display destructing
object. If more than one object is being destroyed the destructors are invoked in
reverse order in which the constructor is called. In the above example s2 will be
destroyed first and then s1 will be destroyed.
Sample Questions
1.

Answer the questions (i) and (ii) after going through the following program :
#include<iostream.h>
#include<string.h>
class product
{
char type[20];
char pname[20];
int qty;
float price;
product()
//function1
{
strcpy(type, Electronic);
strcpy(pname,typewriter);
qty=5;
price=500;
}
public :
void disp()
//function2
{
cout<<type<<<<pname<<:<<qty<<@<<price<<endl;
}
};
void main()
{
product p;
//statement1
p.disp();
//statement2
}
(i)
Will statement1 initialize all the data members for object p with the values
given in the function1 ?(yes OR No). Justify your answer suggesting the
corrections to be made in the above code.
(ii)
What shall be the possible output when the program gets executed? (Assuming
, if required the suggested corrections are made in the program)
Solution
(i)
No. Since the default constructor product() is declared inside private section, it
cannot initialize the objects declared outside the class. Corrections needed are
that the constructor should be declared inside public section.
(ii)
Electronic-typewriter : 5 @ 500
2.

In a class stream with the following details :


Private members:
No
integer
St_name
string of size 20
No_of_stud integer
Amt
integer
Public members:
Class XII-COMPUTER SCIENCE
10

[Type text]
CAMBRIDGE SCHOOL,NOIDA

(i)
(ii)

(iii)
(iv)
(v)
(vi)
(vii)
Solution
(i)

(ii)

(iii)

(iv)

(v)

(vi)

(vii)

Write a constructor to assign initial values where all numeric values


should be zero and strings with null.
Write a parameterized constructor to accept st_name and no_of_stud as
parameters and assign the rest of the numeric data members with 0 and
strings with null.
Write a destructor to display the values of the object being destroyed.
Write a copy constructor for the above class.
Input() to accept all data members .
Display() to display the details
Give statements to invoke all the constructors defined for the above
class.
stream()
{
No=0;
strcpy(St_name,\0);
no_of_stud=0;
Amt=0;
}
stream(char n[],int n1)
{
strcpy(St_name,n);
No=0;
No_of_stud=n1;
Amt=0;
}
~stream()
{
Display();
}
stream(stream &st)
{
No=st.No;
Strcpy(St_name,st.St_name);
No_of_stud=st.No_of_stud;
Amt=st.Amt;
}
void input()
{
cin>>No>>No_of_stud;
gets(St_name);
cin>>Amt;
}
void Display()
{
cout<<No<<No_of_stud;
cout<<No_of_stud;
cout<<Amt;
}
stream s1;
//default constructor invoked
stream s2(science,20);
//parameterized constructor invoked
stream s3(s2);
//copy constructor invoked
Class XII-COMPUTER SCIENCE
11

[Type text]
CAMBRIDGE SCHOOL,NOIDA

3. Answer the questions (i) and (ii) after going through the following program:
class Match
{
int Time;
public:
Match()
//Function 1
{
Time=0;
cout<<Match commences<<end1;
}
~Match()
//Function 2
{
cout<<Unallocatted<<end1;
}
Match(int Duration)
//Function 3
{
Time=Duration;
cout<<Another Match begins now<<end1;
}
Match(Match &M)
//Function 4
{
Time=M.Time;
cout<<Like Previous Match <<end1;
}
};
Match s;
i)
Which member function out of function1, function2, function3,
function4 shown in the above definition of class will be called
automatically , when the scope of an object gets over?
ii)
Match M;
//statement1
Match X(M);
//statement2
Which member function out of function1, function2, function3,
function4
shown in the above definition of class will be called on
execution of statement written as statement2? What is this function called?
iii)
Which feature of object oriented programming is depicted in
Function1,Function 3 and Function4.
Solution
(i)
Function1 which is a default constructor will be invoked and Function2
will be called which is a destructor which will destroy object s.
(ii)
Function4 will be called. This is a copy constructor .
(iii) Polymorphism

Class XII-COMPUTER SCIENCE


12

[Type text]
CAMBRIDGE SCHOOL,NOIDA

1.

2.

3.

Practical Questions
Declare a class address to read and store the address of a person with the data
members
:
name (character string size 20)
House no (int)
Street (character string size 15)
City (character string size 20)
Country(character string size 15)
Include constructor functions . One Default Constructor to assign each data
members to null value (numeric to 0 and string to \0), second one should be a
parameterized constructor to initialize city to DELHI and Country to
INDIA and rest of the data members to user defined parameter values. Also
include the member function which will display the members.
Create a class time that has data members hour, minutes and seconds of int
data types and two constructor functions. One Default constructor should
initialize these data to zero and another parameterized constructor should
initialize these to user supplied values. Also include one member function to
display the data in the format 11:10:59 and another, which will add two
objects of time passed as arguments. Display the value of the added object.
WAP to generate fibonacci series, using a class fib, which have the following
data members and member functions:
Data members
:
first ,second are the first two terms and n is
the no. of terms which should be supplied
into the constructor as parameter.
fib()
:
Constructor function to initialize first and
second to 0 and 1 and n to 10
fib()
:
A parameterized constructor which takes
value of first, second and n from user
gen_fib()
:
Is the function that generates the series for
terms
4. A class circle stores as data member - the radius and area of a circle and two
constructor functions. The first accepts, as argument the radius and calculate
its area. The second is a copy constructor that increases the area of the circle
by 1 and calculates its area. Also include another member function to display
radius and area of the circle

Q 3 and 4 to be done in the practical file

Class XII-COMPUTER SCIENCE


13

Das könnte Ihnen auch gefallen