Beruflich Dokumente
Kultur Dokumente
com)
33
Constructor and
Destructor
Syllabus
Concept of Constructor (Default, Parameterized, copy), Overloaded Constructors,
Constructor with default argument, Destructors. Function overloading, Operator
overloading (overloading unary & binary operators), rules for overloading operators.
Constructors
Q1.What is constructor? State is purpose
Ans.A constructor is special member function whose task is to initialize all the private
data members of the object. It is a special member function because its name is same as
class name. Constructor is invoked whenever an object of its associated, class is
created. It is called as constructor because it constructs the values of data member of
object. The constructor is declared and defined is as follows.
Class abc
{
int a, b;
public:
abc( )
{
}
};
The data members of
an object created by class will be initialized automatically.
for example
main ( )
{ ABC A1;
}
This statement not only creates object A1 but also initialize its data members a and b to
0. There is no need to write any statement to invoke constructor. A constructor that
accepts no parameters is called as Default constructor therefore, the statement ABC
A1 invokes the default constructor.
Example : Consider the following sequence of variable declarations:
Complex
Complex
Complex
Complex
c;
// calls Complex ()
d = 2.0; // calls Complex (double)
i(0, 1); // calls Complex (double, double)
j(i); // calls Complex (Complex const&)
and method
Function
The name of function is different from
the name of class.
They are called, after the objects are
created
Function return a value
They can be declared in the public ,
private or protected section.
Function are used for calculation and
initialization purpose.
Class Demo
{
void getData()
{------------}
int calculate()
{------------}
};
// Parameterized Constructor
void calculate()
{
area = 3.14 * rad * rad ;
circum = 2 * 3.14 *rad ;
}
void dispCircle()
{
cout <<\n Radius = <<rad;
cout <<\n Area = <<area;
cout <<\n Cicrumference = <<circum;
}
};
void main()
{
// Main Program
Circle c1(10);
c1.calculate();
c1.dispCircle();
getch();
}
Q10.Describe the concept of calling the constructor implicitly or explicitly with
the help of c++ code
Ans. For parameterized constructors we must pass initial values as arguments to the
constructor function when an object is created or declared. There are 2 methods to
declare the objects.
1. By calling the constructor explicitly.
2. By calling the constructor implicitly
7
main()
{
SimpleInterest SI1(20,5,2);
SI1.calcualteInt();
SI1.dispData();
// Implicit calling
//Explicit calling
SimpleInterest SI2 = SimpleInterest(10,5,1);
SI2.calcualteInt();
SI2.dispData();
getch();
}
Q11.Describe how multiple constructor can be implemented?
Ans.We can have multiple constructor in a class.Depending on the arguments passed
to the constructor function, we can declare multiple constructors. Consider a
constructor
constr1( ) ;
//with no values, and
constr1(int v1, int v2) ;
}
Q14.Describe the concept of constructor overloading ?
Ans. A constructor for a class is a special member function it is still considered a
function and like all functions in C++ its name can be overloaded. This is the practice of
using a function of the same name but having different types and/or numbers of
parameters:
int func( int a );
double func( double a );
int func( int a, int b );
double func( int a ); // _NOT_ ALLOWED
In the above examples we have three declarations of a function func.
The first two differ in the type of their parameters, the third in the number of
parameters. The fourth example is in fact considered to be equivalent to the first, so is
not allowed. This is because in C++ the return type does _not_ form part of the set of
types considered for differentiating functions having the same name (i.e. overloaded
functions).
Now a class constructor is used to create instances of that class, and is a special
(instance) member function having the same name as the class whose types it is to
create. If a class has no explicitly defined constructors then the compiler will generate
default constructor implementation for the class. These are a default constructor that
takes no parameters at all and does nothing, and a copy constructor that creates a new
instance from an existing one by copying the bits of the existing instance to the new
instance. So even if you define no constructors you have two ways to create a class
instance.
Overloading constructors, like overloading other function names, is just the
practice of defining more than one constructor for a class, each taking a different set of
parameters:
class A
{
public:
A();
// Default constructor
A( A const & other ); // Copy constructor
// ...
};
Above I have defined a class having explicit declarations for the default and copy
constructors. Presumably the implicit implementations are not what are required for
10
// default constructor
a=0;
b=0;
}
};
The default argument constructor can be called with either one or more arguments or
with no arguments.
main ( )
{
ABC a1(10);
ABC a2; //error
}
11
main()
{
SimpleInterest SI1(20,5);
SI1.calcualteInt();
SI1.dispData();
}
//error
int main()
{
int a =10;
f(a);
return 0;
}
void f(int x)
{
cout<<\n In f(int x)\n;
}
void f(int &x)
{
cout<<\n In f(int &x)\n;
}
As the comments in the program describe. two functions cannot be overloaded
when the only difference is that one takes a reference parameter and the other takes a
normal, a call-by-value parameter. In this situation, the compiler has no way of knowing
which version of the function is intended when it is called. Remember, there is no
syntactical difference in the way that an argument is specified when it will be received
by a reference parameter or by a value parameter.
Q19.What is ambiguity in C++ overloaded functions
Ans.
// Sample code for function overloading
void AddAndDisplay(int x, int y)
{
cout<<" C++ Integer result: "<<(x+y);
}
void AddAndDisplay(double x, double y)
{
cout<< " C++ Double result: "<<(x+y);
}
void AddAndDisplay(float x, float y)
{
16
Dynamic Constructor
Q20.What is dynamic constructor? State is purpose
Ans.The constructors can also be used to allocate while creating objects. This will
enable the system to allocate the right amount of memory to each object, when the
objects are of not same size, thus resulting in saving the memory. This allocation of
memory to the object at the time of their construction is called as dynamic construction
of object. The memory is allocated with the help of new operator.
Create a class string with the data member as character pointer. Pointer is
allocated memory at time of construction.
Q21.Write program to demonstrate dynamic constructor
Ans.
Class string
{
char *n[20];
int len;
public:
string()
{
n=\0;
len=0;
}
string (char *s)
{
len=strlen (s);
n=new char[len+1];
strcpy(n,s);
}
void disp()
{
cout<<n;
}
};
void main()
{
char *a;
cin>>a;
17
Person
r(p);
Person
p = q;
= q;
C++ calls a copy constructor to make a copy of an object in each of the above cases. If
there is no copy constructor defined for the class, C++ uses the default copy constructor
which copies each field, ie, makes a shallow copy.
About copy constructor
A copy constructor takes reference to an object of the same class as itself as an
argument.
Example of Copy constructor
#include<iostream.h>
#include <conio.h>
class DemoCopyConstructor
{
private:
int num;
public:
DemoCopyConstructor()
{ }
DemoCopyConstructor(int no)
{
18
\n
\n
\n
\n
Value
Value
Value
Value
of
of
of
of
num
num
num
num
in
in
in
in
object
object
object
object
Dcca = <<Dcca.display();
Dccb = <<Dccb.display();
Dccc = <<Dccc.display();
Dccd = <<Dccd.display();
}
Note : Only reference is passed as an argument to the copy constructor. Value
argument cannot passed as an argument to the copy constructor.
Also A copy constructor is called whenever an object is passed by value, returned by
value or explicitly copied.
Q23.Difference between copy constructor and Assignment
Ans.A copy constructor is used to initialize a newly declared variable from an existing
variable. This makes a deep copy like assignment, but it is somewhat simpler:
1. There is no need to test to see if it is being initialized from itself.
2. There is no need to clean up (eg, delete) an existing value (there is none).
3. A reference to itself is not returned.
Q24.Write program to demostrate copy constructor
Ans.
#include<iostream.h>
#include<conio.h>
class Sample
{
int a;
float b;
19
// copy constructor
Sample::Sample()
{
a=10;
b=20.75;
}
Sample::Sample(Sample &ptr)
{
a=ptr.a;
b=ptr.b;
}
void Sample::display()
{
cout<<"\na : "<<a<<endl;
cout<<"\nb : "<<b<<endl;
}
void main(void)
{
clrscr();
Sample s1;
s1.display();
Sample s2(s1);
s2.display();
getch();
}//end of main
Explanation :
sample ob1 , ob2;
ob1 = ob2;
sample ob3 = ob2;
First case object is created and value are assigned to each member , as member
by member.This is done by overloaded assignment operator not by the copy constructor.
Where as in second case copy constructor is called.Hence Also a copy constructor is
called whenever an object is passed by value, returned by value or explicitly copied.
Destructors
Q25.What is destructor ?State is use
Ans. Destructors are usually used to deallocate memory and do other cleanup for a
class object and its class members when the object is destroyed. A destructor is called
for a class object when that object passes out of scope or is explicitly deleted.
20
// Destructor declaration
};
string::string()
{
length = 0;
s = new char[length + 1];
s[0] = '\0'; // empty string
}
string::string(char *str)
{
length = strlen(str);
s = new char[length + 1];
strcpy(s,str);
}
string::~string()
// Destructor definition
{
delete s;
cout << "One Object deleted...\n";
}
void main(void)
{
clrscr();
string s1("Good "),s2("Morning"),s3;
getch();
}
};
UnarySample:: UnarySample (int x, int y)
{
a1 = x;
b1 = y;
}
void UnarySample::operator - ()
{
a1 = -a1;
b1 = -b1;
}
void UnarySample::print()
{
cout << "a = " << a1 << "\n";
cout << "b = " << b1 << "\n";
}
/*----------------------Definition ends here---------------------*/
void main(void)
{
UnarySample Aobj(100,200);
clrscr();
cout << "Before the application of operator '-'(unary minus) :\n";
Aobj.print();
-Aobj;
// operator function gets invoked
cout << "After the application of operator '-'(unary minus) :\n";
Aobj.print();
Aobj.operator -(); // another way of invoking - as a member function
cout << "After the second application of operator '-'(unary minus) :\n";
Aobj.print();
getch();
}
Output :
Before the application of Operator -(unary minus):
a = 100
b = 200
After the application of Operator -(unary minus):
a = -100
b = -200
After the application of Operator -(unary minus):
a = 100
b = 200
Explanation
28
32
BinarySample temp;
Explanation
When called + overloaded operator as A +B it refers to the B as an argument to be
passed to the function A.operator + (). That is why the second invocation discussed
above is equivalent to A + B. In the body of the function it refers to a and b these are the
data members of object A for which it is invoked.
These refer to the first operand which is object A. The second operand B is passed
as arguments whose data members are accessed as A and B. respectively. A temporary
object of the same type sample is constructed internally and assigned the result of
addition of A and B which then is returned from a function. The assignment C = A + B
assigns the value of temp object to C.
Note here that, the assignment operator = used in the statement C = A + B; is
also overloaded as it assigns values of temp to C object member-by-member.
Q39.Write Program to demonstrate Binary operator Overloading
Ans.
#include <iostream.h>
class MSKsys
{
private:
int x;
int y;
public:
MSKsys()
{
x=0; y=0;
}
void getvalue( )
{
//Constructor
It can be declared either in the public part or in the private part of the class
declaration and will not affect the utility and meaning any way.
37
Is not in the scope of the class and hence can be used as a normal function.
It cannot be called using the object name as it is not a part of the classs objects.
40
42
// Constructor declaration
};
sample::sample()
// Constructor definition
{
strcpy(itemname,"Pencil");
cost = 5;
}
void sample::print_data()
{
cout << "Item : " << itemname << "\n";
cout << "Cost : " << cost << "\n";
}
void main(void)
{
clrscr();
sample A;
A.print_data();
getch();
}
Program-4
Program to demonstrate Friend Function
#include <iostream.h>
#include <conio.h>
class DB;
class DM
{
int meters;
float centimeters;
public:
void getdata()
{
cout<<"\nEnter Meter : ";
cin>>meters;
cout<<"\nEnter Centimeter : ";
cin>>centimeters;
}
friend void add(DM dm, DB db, int ch);
};
class DB
{
int feet;
float inches;
public:
void getdata()
{
cout<<"\nEnter Feet : ";
46
}
Program from the Board Papers
Program-13
Define two functions with same name one returns area of circle whereas another
returns area of rectangle. Test these functions.
Ans.
#include <iostream.h>
#include <conio.h>
float Area(int rad)
{
float area;
area = 3.14 *rad *rad ;
return (area);
}
int Area(int len , int bre)
{
int area;
area = len , bre ;
return (area);
}
void main()
{
cout << \nArea of circle = <<Area(10);
cout<< \nArea of rectangle =<<Area(10,20);
getch();
}
61
66