Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is...

66
Prof.Manoj S.Kavedia (9860174297)([email protected]) 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 c; // calls Complex () Complex d = 2.0; // calls Complex (double) Complex i(0, 1); // calls Complex (double, double) Complex j(i); // calls Complex (Complex const&) 3 3 Constructor and Constructor and Destructor 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. 1

Transcript of Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is...

Page 1: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

ConstructorsQ1.What is constructor? State is purposeAns.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 c; // calls Complex ()Complex d = 2.0; // calls Complex (double)Complex i(0, 1); // calls Complex (double, double)Complex j(i); // calls Complex (Complex const&)

33Constructor and Constructor and

DestructorDestructorSyllabusConcept of Constructor (Default, Parameterized, copy), Overloaded Constructors, Constructor with default argument, Destructors. Function overloading, Operator overloading (overloading unary & binary operators), rules for overloading operators.

1

Page 2: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Each variable declaration implicitly causes the appropriate constructor to be invoked. In particular, the equal sign in the declaration of d denotes initialization not assignment and, therefore, is accomplished by calling the constructor.

Q2.State the difference between constructor and methodAns.

Sr.No Constructor Function1. The name of constructor is same

as the name of class.The name of function is different from the name of class.

2. They are invoked automatically, when the objects are created

They are called, after the objects are created

3. They can not return values. They DONOT have return data types.

Function return a value

4. They must be declared in the public section.

They can be declared in the public , private or protected section.

5. Generally constructor are used for initialization purpose

Function are used for calculation and initialization purpose.

6. Class demo { demo() {---------} };

Class Demo { void getData() {------------} int calculate() {------------} };

Q3.List the characteristics of constructorAns. Characteristics of constructor

1. It should be declared in the public section.2. They are invoked automatically, when the objects are created.3. They do not have return data type i.e they cannot return any value.4. They cannot have inheritance property 5. Like other C++ functions they can have default arguments.6. Constructors cannot refer to their address.7. An object with a constructor cannot be used as a member of ‘union’.8. They make implicit call to operator new and Delete when memory

allocation is required.

Q4.Write C++ program to implement constructorAns.

Class Sample{

public:int a, b ,c;

private:Sample(){

2

Page 3: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

a = 5;b = 5;

}void display(){

c = a + b;cout<<” The Sum of two numbers is : “ << c;

}}

int main(){

Sample s1;s1.display();return 0;

}

Q5.List different types of ConstructorAns. There are different types of Constructors :

1. Default Constructor2. Parameterized constructor3. Copy constructor4. Default Value constructor and 5. Dynamic Constructor

Q6.What is default constructor? state its useAns. The constructor which takes no arguments is called the default constructor . E.g., the default constructor is invoked when a variable is declared like this:

Student S1;In fact, the compiler will generate its own default constructor for a class provided that no other constructors have been defined by the programmer. The compiler generated default constructor initializes the member variables of the class using their respective default constructors.

ExampleClass employee

{ private : int bsal;

public : employee() //default Constructor

{bsal=4000;

} void display()

{ -----------}}

3

Page 4: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

About Default constructor in C++C++, the standard describes the default constructor for a class as a constructor that can be called with no arguments (this includes a constructor whose parameters all have default arguments.In C++, default constructors are significant because they are automatically invoked in certain circumstances:

• When an object value is declared with no argument list, e.g. MyClass x;; or allocated dynamically with no argument list, e.g. new MyClass; the default constructor is used to initialize the object

• When an array of objects is declared, e.g. MyClass x[10];; or allocated dynamically, e.g. new MyClass [10]; the default constructor is used to initialize all the elements

• When a derived class constructor does not explicitly call the base class constructor in its initializer list, the default constructor for the base class is called

• When a class constructor does not explicitly call the constructor of one of its object-valued fields in its initializer list, the default constructor for the field's class is called

• In the standard library, certain containers "fill in" values using the default constructor when the value is not given explicitly, e.g. vector<MyClass>(10); initializes the vector with 10 elements, which are filled with the default-constructed value of our type.

In the above circumstances, it is an error if the class does not have a default constructor.

The compiler will implicitly define a default constructor if no constructors are explicitly defined for a class. This implicitly-declared default constructor is equivalent to a default constructor defined with a blank body. (Note: if some constructors are defined, but they are all non-default, the compiler will not implicitly define a default constructor. This means that a default constructor may not exist for a class.)

Q7.Write c++ program to demonstrate default constructorAns.

Class Sample{

public:int a, b ,c;

private:Sample() // Default Constructor{

a = 5;b = 5;

}void display(){

c = a + b;cout<<” The Sum of two numbers is : “ << c;

}}

4

Page 5: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

int main(){

Sample s1;s1.display();return 0;

} One More example for Default constructor

#include<iostream.h>#include<conio.h>#include<string.h>class bank{

private:char name[20],type[20];int acno,bal,wit,dep;

public:bank() // Default Constructor {

strcpy(name,"ManojKavedia");acno=5;bal=5000;strcpy(type,"Saving");

}void deposit(){

cout<<"\nEnter amt to deposit :";cin>>dep;bal=bal+dep;show();

}void withdraw(){

cout<<"\nEnter amt to withdraw :";cin>>wit;if(bal-wit>=500)

bal=bal-wit;else

cout<<"\nYou cannot withdraw";show();

}void show(){

cout<<"\nDepositor name :"<<name<<endl; cout<<"\nBalance :"<<bal<<endl;

}};void main(){

5

Page 6: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

bank bk; clrscr(); bk.deposit(); bk.withdraw(); getch();

}

Parameterized Constructor

Q8.What is parameterized constructor? state its useAns.Default constructor are used initializes the data members of the objects to zero. Or any other value. C++ permits the constructors that can take arguments. Such constructors are called as parameterized constructors.Example :

Class ABC{ int a, b;

public:ABC (int x, int y){

a=x; b=y;

};.}

For such 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.ABC a1 = ABC(10,20);

2. By calling the constructor implicitlyABC a2 (30,40);

It is possible to define constructor with default arguments as given below;Example :

ABC (int x , int y = 40) {

a = x;b = y;

}The default value of argument int y is given to the private data member b;

main (){

ABC a1(10);ABC a2(20,30);

}The value of object a1 is a=10, b=40.While for object a2 the values are a=20, b=30.

6

Page 7: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

It is important to distinguish between the default constructor & default argument constructor.

Q9.Write c++ program to demonstrate parameterized constructorAns. Program find area and circumference of the circle

class Circle{

private :int rad;float area , circum;

public:circle()

{rad =0 ; // Default Constructor

}

circle(int r){ rad = r ; // 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); //calling parameterized constructorc1.calculate();c1.dispCircle();getch();

}

Q10.Describe the concept of calling the constructor implicitly or explicitly with the help of c++ codeAns. 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

Page 8: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Program to calculate simple interest Class Simple_Interest

{ private :

int prin , rate , noy;float Sint;

public :Simple_Interest( int p , int r , int y)

{prin = p ;rate = r;noy = y;

}float calculateInt()

{ Sint = (prin * rate * noy) / 100 ;

}

void dispData(){ cout <<”\nPrinciple Amount = “<<prin; cout <<”\nRate of interest =”<<rate; cout <<”\nNumber of Year =”<<noy; cout <<”\n Simple Interest =”<<calculateInt();}

};

void main(){ SimpleInterest SI1(20,5,2); // Implicit calling

SI1.calcualteInt(); SI1.dispData();

//Explicit callingSimpleInterest 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) ; //with two integer values as parameter.

8

Page 9: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

In main(), we can create a object without parameter specification and also other object can be created alongwith parameter values to be initialized. As per the call, the relative constructor function will be called.

That means, as we write the argument (s), compiler automatically decides the constructor call.

Hence the declarationconstr1 C1; will invoke the first constructorconstr1 C2(10,20) will invoke the second constructor since it receives two

arguments.

Q12.Write c++ program to implement multiple constructors? OrQ13.write program to demonstrate Constructor Overloading Ans.

class maximum{

public:maximum()

{cout<<”\n In sufficient argument”;

}maximum(int a , int b)

{cout <<”\n Maximum of Two Numbers =”;if (a>b) {

cout<<”\n Number1 is maximum”; }else {

cout<<”\n Number 2 is maximum; }

}

maximum(int a , int b , int c ){

cout <<”\n Maximum of Three Numbers =”;if (a>b && a >c) {

cout<<”\n Number1 is maximum”; }elseif (a>b && a>c) {

cout<<”\n Number 2 is maximum; }else {

cout<<”\n Number 3 is maximum;9

Page 10: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

}};

void main()

{maximum m1(); //Calling default constructor

maximum m2(10,20); //calling parameterized // constructor

maximum m3(20,40,60);getch();

}

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_ ALLOWEDIn 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

Page 11: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

class A. Note: the constructor definitions will be assumed to exist elsewhere.The need for this should be obvious - to allow a class to be created from various parameters (or none at all). For example objects of type A can be created like so:

A an_a; // default constructed A an_a_copy( an_a ); // copy constructedHence a constructor can be overloaded like a member function. ie when a program has more then one constructor , constructor overloading takes place.

Default argument constructor

Q15.Describe how a constructor is defined with default argumentAns. It is possible to define constructor with default arguments as given below;Example :

ABC (int x , int y = 40) {

a = x;b = y;

}The default value of argument int y is given to the private data member b;

main (){

ABC a1(10);ABC a2(20,30);

}The value of object a1 is a=10, b=40.While for object a2 the values are a=20, b=30.

Example. ABC (int x=10; int y=40) // default value constructor

{a=x;b=y;

}

ABC ( ) // 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

Page 12: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

The object a1 calls the default argument constructor while the statement abc a2; causes the ambiguous situation whether to call default argument constructor or default constructor.

Q16.Write c++ program to implement default argument constructor?Ans.Program to calculate simple interest

Class Simple_Interest{ private :

int prin , noy;float Sint , rate;

public :Simple_Interest( int p , int y , int r=0.2) //Default value Constr

{prin = p ;rate = r;noy = y;

}

float calculateInt(){

Sint = (prin * rate * noy) / 100 ;}

void dispData(){ cout <<”\nPrinciple Amount = “<<prin; cout <<”\nRate of interest =”<<rate; cout <<”\nNumber of Year =”<<noy; cout <<”\nSimple Interest =”<<calculateInt();}

};

void main(){ SimpleInterest SI1(20,5);

SI1.calcualteInt(); SI1.dispData();

}

Q17.What dynamic initialization of object describe with exampleAns.Class objects can be initialized dynamically. That is to say, the initial value at an object may be provided during run time.

Main advantage at dynamic initialization is that we can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format at data at run time depending upon the situation.

Example12

Page 13: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

#include<iostream.h>class Account{

int acc_no;float amount;char acc_type;public:Account()

{ }Account(int no,float bal,char type='S'){

acc_no=no;amount=bal;acc_type=type;

}void display(){

cout<<"\nAccount No. : "<<acc_no;cout<<"\nBalance : "<<amount;cout<<"\nAccount Type : "<<acc_type;

}};void main(){

Account a1,a2;int no;float bal;char type;cout<<"\nEnter Account Number, Balance and Account type";cin>>no>>bal>>type;a1=Account(no,bal,type);cout<<"\nEnter Account Number, Balance";cin>>no>>bal;a2=Account(no,bal);a1.display();a2.display();

}

Depending on the value given to acc_type behavior of the program can change. This program has two constructor. First constructor is default constructor and second is parameterized constructor with one default argument. This parameter value is to be given at rum time which is provided by the user. Q18.Describe the ambiguity in function overloading.Ans.There is situation in which the compiler is unable to choose between two(or more) overloaded functions. When this happens, the situation is said to be ambiguous. Ambiguous statement are errors,and program contain ambiguity will not compile.

13

Page 14: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

By far the main cause of ambiguity involves c++’s automatically type conversions. As you know, c++ automatically attempts to convert the argument used to call a function into the type of argument expected by the function. For example, consider this fragment

int myfunc(double d)//-------------

cout<<myfunc(‘c’); //not an error , conversion appliedAs the comment indicates, this is not an error because c++ automatically converts

the character c into its double equivalent. In C++, very few type conversion of this sort are actually disallowed.

Although automatically type conversion are convenient, they are also a prime cause of ambiguity. For example, consider the following program.

#include<iostream.h>Using namespace std;float myfunc(float i);double myfunc(double i);int main(){

cout<<myfunc(10.1)<<“ ”;//unambiguous , calls myfunc(double)cout<<myfunc(10); // ambiguousreturn 0;

}

float myfunc(float i){

return i;}

double myfunc(double i){

return i;}

Here myfunc() is overloaded so that it can take argument of either type float or

type double. In the unambiguous line myfunc(double) is called, unless explicitly specified as float, all floating point constant in c++ are automatically of type double. Hence that call is unambiguous. However when myfunc() is called by using the integer 10, ambiguity is introduced because the compiler has no way of knowing whether it should be converted to a float or to a double. This cause an error message to be displayed, and the program will not compile.

As the preceding example illustrate, it is not the overloading of myfunc() relative to double and float that causes the ambiguity.Rather it is the specific call to myfunc() using an indeterminate type of argument that causes the confusion.Put differently the error is not caused by overloading of myfunc(),but by the specific invocation.

Here is another example of ambiguity caused by C++s automatic type conversionsExample

#include <iostream.h>using namespace std;

14

Page 15: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

char myfunc(unsigned char ch)l char myfunc(char ch);int main(){

cout << myfunc(c); // this calls myfunc(char)cout << myfunc(c); // ambiguousreturn 0;

}char myfunc (unsigned char ch)

{return ch-1;

}char myfunc (char ch)

{return ch+1;

}

In C++, unsigned char and char are not inherently ambiguous However, when myfunc() is called by using the integer88, the compiler does not know which function to call. That is, should 88 be converted into a char or an unsigned char?

Ambiguity is by using default arguments in overload functions. To see how, examine this program:

#include <iostream.h>using namespace std;int myfunc(int i);in myfunc(int i, tnt j)int main()

{cout << myfunc(4, 5) << “”; // unambiguouscout << myfunc(1O); // ambiguousreturn 0;

}

int myfunc(int i){

return i;}

int myfunc(int i , int j){

return i*j;

}Here, in the first call to myfunc( ), two arguments are specified; therefore, no

ambiguity is introduced and myfunc(int i, int j) is called. However, when the second myfunc() is made, ambiguity occurs because the compiler does not know to call the

15

Page 16: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

version of myfunc( ) that takes one argument or to apply the default ie version that takes two arguments.

Ambiguity - overloaded functions. For example, consider this program.#include<iostream.h>using namespace std;

void f(int x);void f(int &x); //error

int main(){

int a =10;f(a); // error which f() is to be calledreturn 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 functionsAns.

// 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

Page 17: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

cout<< " C++ float result: "<<(x+y); }

Some times when these overloaded functions are called, they might cause ambiguity errors. This is because the compiler may not be able to decide what signature function should be called.

Dynamic Constructor

Q20.What is dynamic constructor? State is purposeAns.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 constructorAns.

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

Page 18: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

string s1 (a); //dynamic initializationstring s2 (“Hello ! ”);s1.disp();s2.disp();}

Copy Constructor

Q22.What is copy constructor?Describe with example?Ans. Copy constructor is a type of constructor which constructs an object by copying the state from another object of the same class. Whenever an object is copied, another object is created and in this process the copy constructor gets called.

A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).A variable is declared which is initialized from another object, eg,

•Person q("ManojKavedia"); // constructor is used to build object q.

•Person r(p); // copy constructor is used to build object r.

•Person p = q; // copy constructor is used to initialize in declaration.

•p = q; // Assignment operator, no constructor or copy constructor.

• A value parameter is initialized from its corresponding argument.

f(p); // copy constructor initializes formal value parameter.

• An object is returned by a function.

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 constructorA 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

Page 19: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

num = no;}

DemoCopyConstructor(DemoCopyConstructor &no){

num = no.num;}

void display(void){

cout << num ;}

};

void main(){

DemoCopyConstructor Dcca(143); // object Created and InitializedDemoCopyConstructor Dccb(Dcca); // Copy constructor invokedDemoCopyConstructor Dccc = Dcca; // Copy constructor invoked

DemoCopyConstructor Dccd; // object created but not intializedDccd = Dcca ; // Copy constructor not invoked

Cout << “\n Value of num in object Dcca = “<<Dcca.display(); Cout << “\n Value of num in object Dccb = “<<Dccb.display(); Cout << “\n Value of num in object Dccc = “<<Dccc.display(); Cout << “\n Value of num in object Dccd = “<<Dccd.display(); getch();

}

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 AssignmentAns.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 constructorAns.

#include<iostream.h>#include<conio.h>

class Sample{

int a;float b;

19

Page 20: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

public:Sample(); //constructorSample(Sample &ptr); // copy constructor

void display();};// end of class

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; // object created not initialized

ob1 = ob2;sample ob3 = ob2; // object initialized with copy constructor

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 useAns. 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

Page 21: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

The destructors as the name implies are used to destroy the object that has been created by the constructors. Like the constructor destructor is a member function whose name is same as class name but by preceded by a tilde (~) sign.

Example : the destructor for class ABC is given as;Class ABC{public:ABC( ); //Constructor{ }

~ABC( ); //Destructor{ }};A destructor never takes any arguments nor does it return any value. It is invoked

implicitly by compiler on exit of the program. It deallocates the memory of the object that is no longer needed. We can use delete operator to free that memory in the destructor.

Example In class string a new operator was used to allocate a memory to a pointer so a

destructor should have a delete operator to destroy memory of pointer as given below.

Class string{public:~string ( ) //destructor{delete n;}};

Note : A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const, volatile, const volatile or static. A destructor can be declared virtual or pure virtual.If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor. This implicitly declared destructor is an inline public member of its class.

21

Page 22: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Q26.Write c++ program to demonstrate the use of destructorAns.

/* Program Destructor Illustrated */#include <iostream.h>#include<conio.h>int no_of_objects = 0; // Global Declarationclass sample{

public:sample();~sample(); // Destructor Declaration

};sample::sample(){

no_of_objects++;cout << "No of object created " << no_of_objects;cout << "\n";

}sample::~sample() // Destructor Definition{

cout << "No of object Destroyed " << no_of_objects;cout << "\n";no_of_objects--;

}void main(void){ clrscr();

void function(); // prototypecout << "\nMAIN Entered\n";sample s1, s2, s3;{

cout << "\nBLOCK-1 Entered\n";sample s4, s5;

}function();{

cout << "\nBLOCK-2 Entered\n";sample s7;

}cout << "\nMAIN Re-Entered\n";

getch();}void function(){

cout << "\nFUNCTION Entered\n";22

Page 23: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

sample s6;}

output :MAIN EnteredNo. of object created 1No. of object created 2No. of object created 3

BLOCK-1 EnteredNo. of object created 4No. of object created 5No. of object Desctroyed 5No. of object Desctroyed 4

FUNCTION EnteredNo. of object created 4No. of object destroyed 4

BLOCK-2 EnteredNo. of object created 4No. of object Desctroyed 4

MAIN Re-EnteredNo. of object destroyed 3No. of object destroyed 2No. of object destroyed 1

ExplanationThe message “MAIN Entered” is displayed followed by construction of objects s1,

s2 and s3. Then the first block is entered. Within the block two objects are created invoking the constructor. See that when the program control comes out of the block those two objects are destroyed.

Similarly when the control transferred to the function a new object within the function gets created. When function returned the object gets destroyed. Similarly the second block entered creating one object When compiler sees the end of the black marked by ‘}’ the object is destroyed. When program returns, the remaining three objects gets destroyed whose scope is the main () function.

Q27.Write a program to demonstrate the use of constructor and destructor for string operationAns. /* Program Destruction using 'delete' Operator */

#include <iostream.h>#include <string.h>#include <stdlib.h>#include<conio.h>class string

23

Page 24: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

{char *s;int length;

public:string();string(char*);~string(); // 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();

}

Q28.List the syntax rules for writing destructorAns.The rules for writing a desctructor function are

1. A destructor function name is same as that of the class it belongs except that the first character of the function must be tilde(~) sign.

2. It is declared with no return types (not even void) since it cannot ever return a value

3. It cannot be declared static ,const or volatile4. It takes no argument and therefore cannot be overloaded5. It should have public access in the class declaration

Q29.List the situation when a destructor function is invokedAns.Following are the situation when destructor function are invoked

24

Page 25: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

1. After the end of main() for all static , local to main() and global instance of the class.

2. At the end of each function containing an argument of class.3. At end of each block containing an argument of class after their use.4. To destroy any unnamed temporaries of class after their use.5. When an instance of class allocated on the heap is destroyed via delete

Operator OverLoadingQ30.What is Operator overloading? Ans. C++ tries to make the user-defined data types behave in much the same as the built-in types. For instance, C++ permits us to add 2 variables of user-defined types with the same syntax that is applied to the basic types. This means that C++ has ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meaning to an operator is known as operator overloading.

Operator overloading provides a flexible option for the creation of new definitions for most of the c++ operators. One can almost create a new language of our own by the creative use of the function and operator overloading techniques. operator overload all the C++ operators except the following:

:: //scope resolution operator?: //ternary operatorsizeof( ) //size of operator.* or -> * //pointer operator. //Dot operatorNote that the operator symbols can be overloaded means a different semantics

(meaning) can be given or attached to those symbols. It can be done in the similar way we overload functions. Here as the operator symbols are standard and defined by C++ we cannot change their syntax of usage. Only different contexts in which the overloaded operators are used, invoke the appropriate meaning. When the operator is overloaded its original meaning defined by C++ is not changed or lost. It still can be used for the purpose for which it is defined by the language. For example, an operator ‘+‘ can be overloaded to concatenate two string operands but still it can be used to add two integers in the normal way.

Q31.How processing of overloading is doneAns. Processing of overloaded Operator

Create a class that define data type that has to be used in the overloading operation.

Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function.

Define the operator function to implement the required operations.

Q32.List types of operator overloadingAns.There are two types of operators;

UnaryBinaryOverloading unary operator operates on a single operands.When overloading using member functions no arguments are passed to the

operator function.25

Page 26: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

When overloading using friend function one argument is passed to the operator function.

The syntax to overload operator isReturn type Operator op( );{ //function definition }If overloading friend function friend return type operator op (one bit){ //function definition}

Accessing the operator the syntax is;x.op; or op.x;where op is operator x is object which works on it.

Q33.Which are the operator which cannot be overloadedAns.

The following operators cant be overloaded;:: //scope resolution operator?: //ternary operator( ) //size of operator.* or -> * //pointer operator. //Dot operator

Q34.List the rules for Operator OverloadingAns.Rules for operator’s overloading

Only existing operators can be overloaded. The overloaded operator must have at least one operand i.e. of user defined data type. We should not change the basic meaning of operator.

Overloaded operators follow the syntax rule of original operators.There are some operators that cannot be overloaded. Those are sizeof, . , .* , ?:

and ::.We cannot use friend function to overload certain operators i.e. assignment

operator(=), function call operator ( ), subscript operator [ ] and dereferencing operator ->.

Unary operators are overloaded by means of member function, no explicit arguments are passed but by means of friend function it takes one reference argument.

Binary operators are overloaded through the friend function that takes 2 explicit arguments and by means of member function it takes one explicit argument.

When using binary operators through a member function, the left-hand operand must be an object of that class.

26

Page 27: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Binary arithmetic operator i.e. =, -, *, / must explicitly return a value and must not attempt to change their own argument.

Q35.Describe the syntax of operator overloadingAns. The key to overload an operator is to associate the operator function with a classobject. The operator thus can be given different meaning but in the context of the class for which it is defined. The operator function can be defined as follows:

return-type classname::operator operator-symbol(argument list){

function body;}

Explanation The way operator function is defined, is similar to a member function definition or

a constructor definition. The major difference is in the name of the operator function. As the operator is a standard C++ symbol; the function name is given as, “operator <operator-symbol>” i.e. the word operator immediately followed by the standard operator symbol. For example, the operator function name corresponding to operator ‘+‘ is written as ‘operator +‘. Similar the overloaded operator function for operator ‘-‘ (minus) has name operator - and so on.

Remember that operator function is either non-static member functions or friend functions. The operator which is overloaded can be either unary or binary.

A basic difference between them is that a friend function will have only one argument for unary operators and two for binary operators, while a member function has no arguments for unary operators and only one for binary operators. This is because the object used to invoke the member function is passed implicitly and therefore is available for the member function. This is not the case with friend functions. Arguments may be passed either by value or by reference.

Q36.Describe overloading of UNARY operator with exampleAns.Unary operators work only with a single operand. For example. unary minus ‘-’ operator changes the sign of the operand If we define an overloaded unary operator the only operand it can work on is the object itself for which it is defined and hence do not take any additional arguments.

Example/* Unary Operator Overloading */#include <iostream.h>#include<conio.h>/*----------------------Class definition-------------------------*/class UnarySample{

int a1;int b1;

public :UnarySample () { } // default empty constructorUnarySample (int, int);

27

Page 28: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

void operator - (); // Overloaded unary minusvoid print();

};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 invokedcout << "After the application of operator '-'(unary minus) :\n";Aobj.print();Aobj.operator -(); // another way of invoking - as a member functioncout << "After the second application of operator '-'(unary minus) :\n";Aobj.print();getch();

}

Output :Before the application of Operator ‘-‘(unary minus):a = 100b = 200

After the application of Operator ‘-‘(unary minus):a = -100b = -200

After the application of Operator ‘-‘(unary minus):a = 100b = 200

Explanation28

Page 29: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

In the program void is the return type, Unarysample is the classname. Operator function name is operator ‘-’. As it is a unary operator do not take any argument, simply work on associated object. It is invoked as,

-Aobj;in the program. This means the syntax of the unary minus is used, but as the

operand is an object of type sample the operator function operator — () gets invoked for object A. in the above program the unary minus operator is overloaded to work with object operands of user defined type Unarysample.

The same operator function can also be invoked as a simple member function. Aobj.operator –();The resultant effect is same.

Q37.Write the program to demonstrate the Unary operator Ans. To increment the object of the class counter which has data members as count initialize the object using constructor

Class counter { private :int count;public:counter operator++ ( ){counter temp;temp.count= + count;return(temp);}

counter (int c){count=c;}counter operator++ (int a){counter temp;temp.count=count++;return(temp);}void disp(){cout<<count;}

counter(){count=0;}};void main(){

29

Page 30: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

counter c1,c2;c1++;++c2;c3=c1++;c4=++c1;c1.disp();c2.disp();c3.disp();c4.disp();}

output1111

Q38.Describe overloading of BINARY operator with exampleAns. Binary-operator which require to work on two operands, use one operand - the object for which it is invoked and other operand - the argument explicitly passed to it. For example, the overloaded binary ‘+‘ operator.

BinarySample BinarySample:: operator + (BinarySample obj){

------------------------------------------

}takes the object argument of type ‘BinarySample’. It adds the current object’s data member (from which it is invoked) to the argument object’s data members and stores the result in a temporary object and return that object as a resultant value of the addition.

Example /* Binary '+' Operator Overloading */#include <iostream.h>/*----------------------Class definition-------------------------*/class BinarySample{

int a;int b;

public :BinarySample () { } // default empty constructorBinarySample (int, int);

// Overloaded binary addition operatorBinarySample operator + (sample);void print();

};30

Page 31: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

BinarySample:: BinarySample (int x, int y){

a = x;b = y;

}

// Overloaded binary addition operator as a member function// Returns an object as a value of the additionBinarySample BinarySample::operator + (BinarySample x){

BinarySample temp;temp.a = a + x.a;temp.b = b + x.b;return temp;

}void BinarySample::print(){

cout << "a = " << a << "\n";cout << "b = " << b << "\n";

}/*----------------------Definition ends here---------------------*/void main(void){

BinarySample A(500,100), B(50,50), C;cout << "The result of the addition is :\n";C = A + B; // invocation of the operator functionC.print();cout << "\nSecond method of invocation of operator function- \n";cout << "The result of the addition is :\n";C = A.operator + (B); // different way of invocationC.print();

}

Output :The result of the addition is

A = 550B = 150

Second Method of invocation of operator function –A = 550B = 150

ExplanationThe calling of the binary ‘+’ operator overloaded as a member function. It can be

either calledA + B

Or like this31

Page 32: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

A.operator +(B)Both the way will result in the same output.

32

Page 33: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

ExplanationWhen 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 OverloadingAns.#include <iostream.h>class MSKsys{ private: int x; int y;

public: MSKsys() //Constructor { x=0; y=0; }

void getvalue( ) //Member Function for Inputting Values {

BinarySample BinarySample::operator + (BinarySample x)

BinarySample temp;

33

Page 34: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

cout << “\n Enter value for x: “; cin >> x; cout << “\n Enter value for y: “; cin>> y; }

void displayvalue( ) //Member Function for Outputting Values { cout <<”value of x is: “ << x <<”; value of y is: “<<y }

MSKsys operator +(MSKsys);};

MSKsys MSKsys :: operator + (MSKsys e2) //Binary operator overloading for + operator defined { int x1 = x+ e2.x; int y1 = y+e2.y; return MSKsys(x1,y1); }

void main( ) { MSKsys e1,e2,e3; //Objects e1, e2, e3 created cout<<\n”Enter value for Object e1:”; e1.getvalue( ); cout<<\n”Enter value for Object e2:”; e2.getvalue( ); e3= e1+ e2; //Binary Overloaded operator used cout<< “\nValue of e1 is:”<<e1.displayvalue(); cout<< “\nValue of e2 is:”<<e2.displayvalue(); cout<< “\nValue of e3 is:”<<e3.displayvalue();}

The output of the above program is:

Enter value for Object e1:Enter value for x: 10Enter value for y: 20Enter value for Object e2:Enter value for x: 30Enter value for y: 40Value of e1 is: value of x is: 10; value of y is: 20Value of e2 is: value of x is: 30; value of y is: 40Value of e3 is: value of x is: 40; value of y is: 60

Explanation

34

Page 35: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

In the above example, the class MSKsys has created three objects e1, e2, e3. The values are entered for objects e1 and e2. The binary operator overloading for the operator ‘+’ is declared as a member function inside the class MSKsys. The definition is performed outside the class MSKsys by using the scope resolution operator and the keyword operator.

The important aspect is the statement: e3= e1 + e2;

The binary overloaded operator ‘+’ is used. In this statement, the argument on the left side of the operator ‘+’, e1, is the object of the class MSKsys in which the binary overloaded operator ‘+’ is a member function. The right side of the operator ‘+’ is e2. This is passed as an argument to the operator ‘+’ . Since the object e2 is passed as argument to the operator’+’ inside the function defined for binary operator overloading, the values are accessed as e2.x and e2.y. This is added with e1.x and e1.y, which are accessed directly as x and y. The return value is of type class MSKsys as defined by the above example.

Friend Function Q40.What is Friend Function ?State its purpose?Ans.Private members can not be accessed from outside the class i.e. a non member function can not have an access to the private data of a class. Now if we want two classes to share a particular function, c + + allows the common function to be made friendly with both the classes thereby allowing the function to have access to the private data of these classes. Such a function need not be member of any of these classes.

Syntax friend data_type function_name ( ) ;

The function declaration should be preceded by the keyword friend.

Example/* Friend Functions */#include <iostream.h>#include<conio.h>class time{

int seconds;public :

void set(int);friend void print_time(time); // Friend function Declaration

};void time::set(int n){

seconds = n;}void disp_time(time dt) // Friend function definition{

35

Page 36: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

int h = dt.seconds / 3600, // Friend function can accessm = (dt.seconds % 3600) / 60; // private data memberscout << "Time : " << h << ":" << m << "\n";

}void main(void){

clrscr();time current_time;current_time.set(12000);disp_time(current_time);getch();

}

ExplanationIn the example program a friend function disp_time() for the class time. In the

declaration the word friend before the function header. The word friend should not be used again while defining the function. The definition which is accessing the private data member seconds through the objects name which is passed to the function as, dt.seconds. This otherwise is not possible for any other common function outside the class definition.

The function disp_time() is invoked from main() function like any other function.Hence member function of one class can be friend function of another class.

Q41.Write Program to demonstrate friend function used for Multiple classes?Ans. When we need to write a function which needs to operate on objects of those two classes, then there is only one way to declare them as a friend function. The same function hence can be declared as a friend to both these classes and now it can access the private members of both these classes.

/* Friend function between different classes */#include <iostream.h>#include<conio.h>class date; // declaration to spread the forward referenceclass time

{int seconds;

public :void set(int);friend void print_datetime(date,time);

};void time::set(int n){

seconds = n;}class date{

int day, month, year;public :

36

Page 37: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

void set(int, int, int);friend void print_datetime(date,time);

};void date::set(int d, int m, int y){

day = d; month = m; year = y;}void print_datetime(date d, time t) // Friend function definition{

int h = t.seconds / 3600,m = (t.seconds % 3600) / 60;

cout << "Date : " << d.day << "/"<< d.month << "/"<< d.year << "\n";

cout << "Time : " << h << ":" << m << "\n";}void main(void){

clrscr();date todays_date;time current_time;todays_date.set(16,2,2002);current_time.set(12000);print_datetime(todays_date, current_time);getch();

}

Explanation In the example the friend function print_datetime () acts as a link between the two

classes and accesses the private members of both the classes. In the program above there is a declaration at the top,

class date; // declaration to make the forward reference

This declaration is required, to take care of the forward reference. When declaring the class time there is a friend function declaration,

friend void print_datetime (date, time);At this time, the compiler will not know what date is, unless we explicitly declare at least that, date is a class, as we did. Otherwise, compiler will throw an error. Thus, the use of a date class even before its declaration is called forward reference. The declaration at the top thus will help compiler to state that forward reference.

Q42.What are the characteristic of Friend functionAns. Friend function characteristics

• Can access the members (private as well as public) of the class directly using the object’s name. e.g. objectl.a and soon.

• 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

Page 38: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

• Can accept the objects as arguments when declared to do so.• 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 class’s objects.

Operator Overloading with Friend FunctionQ43.How unary operator overloading can be done with friend function , describe with example?Ans. An operator function can either be a non static member function or a friend function Let us now see how an operator function of an overloaded unary minus can be written.

As a friend function can work on the object of type class for which it is declared as a friend, it can be declared to accept the object as an argument as demonstrated in following program

/* Overloading Unary Operator as a Friend Function */#include <iostream.h>#include<conio.h>/*----------------------Class definition-------------------------*/class UFsample{

int a;int b;

public :UFsample() { } // default empty constructorUFsample(int, int);

// Overloaded unary minus as a friendfriend void operator - (UFsample &);void print();

};UFsample::UFsample(int x, int y){

a = x;b = y;

}void UFsample::print(){

cout << "a = " << a << "\n";cout << "b = " << b << "\n";

}/*----------------------Definition ends here---------------------*/void operator - (UFsample &x) // friend function definition{

x.a = -x.a;x.b = -x.b;

}void main(void){

38

Page 39: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

UFsample A(10,20);clrscr();cout << "Before the application of operator '-'(unary minus) :\n";A.print();-A; // invoking operator functioncout << "After the application of operator '-'(unary minus) :\n";A.print();operator -(A); // another way of invoking - as a member functioncout << "After the second application of operator '-'(unary minus) :\n";A.print();getch();

}

ExplanationA friend function operator — () is defined. There is a difference that the operator

function as a member function do not take any parameter, whereas, operator function as a friend takes a single parameter. The reason is a member function within its body can directly refer to the data members. Friend function being external to the class requires to take single object argument to operate on. The overloaded operator function is declared as a friend by writing keyword friend in the declaration as,

Friend void operator –(UFsample &);why a reference to an object is passed to the function? Because the operator

function acts on the object and modify the object. The modification within the friend operator function is possible only when it has the reference of that object.

Also the invocation of the friend operator function is same as that of operator function which is implemented as a member function of a class.

Q44.How Binary operator overloading can be done with friend function , describe with example?Ans.Friend function can be used in place of member function for overloading binary operator , the only difference is that a friend function requires two arguments to be explicitly passed to it, while a member function requires only one.

/* Overloading Binary '+' Operator as a friend function */#include <iostream.h>#include<conio.h>/*----------------------Class definition-------------------------*/class BFsample{

int a;int b;

public :BFsample() { } // default empty constructorBFsample(int, int);

// Overloaded binary addition operator as a friendfriend BFsample operator + (BFsample, BFsample);void print();

39

Page 40: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

};BFsample::BFsample(int x, int y){

a = x;b = y;

}void BFsample::print(){

cout << "a = " << a << "\n";cout << "b = " << b << "\n";

}/*----------------------Definition ends here---------------------*/// Overloaded binary addition operator as a friend function// Returns an object as a value of the additionBFsample operator + (BFsample p, BFsample q){

BFsample temp;temp.a = p.a + q.a;temp.b = p.b + q.b;return temp;

}void main(void){ clrscr();

BFsample A(450,120), B(75,45), C;cout << "The result of the addition is :\n";C = A + B; // invocation of the operator functionC.print();

cout << "\nSecond method of invocation of operator function-\n";cout << "The result of the addition is :\n";C = operator + (A,B); // different way of invocationC.print();

}

ExplanationThe operator ‘+’ is overloaded as a friend function, returning object of type

BFsample as a result of addition. It takes two arguments which acts as operands to the‘+‘(plus) operator. The operator function constructs a temporary object and store the result of addition into it. It finally returns the temporary object which gets assigned to C when executed the statement C = A + B. The different calling of the operator function,

C = operator + (A. B);It is called with two object parameters A and B. The calling was.

C = A.operator +(B)That is because of the member function there. In this program it is a friend and friend is not part of the class and hence can be independently invoked without a object name attached to it.

40

Page 41: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Q45.Program to demonstrate overloading of BINARY operator with Friend Function with exampleAns. /* Overloading Binary '+' Operator as a friend function */

#include <iostream.h>/*----------------------Class definition-------------------------*/class sample{

int a;int b;

public :sample() { } // default empty constructorsample(int, int);

// Overloaded binary addition operator as a friendfriend sample operator + (sample, sample);void print();

};sample::sample(int x, int y){

a = x;b = y;

}void sample::print(){

cout << "a = " << a << "\n";cout << "b = " << b << "\n";

}/*----------------------Definition ends here---------------------*/// Overloaded binary addition operator as a friend function// Returns an object as a value of the additionsample operator + (sample p, sample q){

return sample(p.a+q.a, p.b+q.b);}void main(void){

sample A(5,10), B(5,5), C;cout << "The result of the addition is :\n";

41

Page 42: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

C = A + B; // invocation of the operator functionC.print();cout << "\nSecond method of invocation of operator function-\n";cout << "The result of the addition is :\n";C = operator + (A,B); // different way of invocationC.print();

}

Q46.What is type casting? Explain with example?Ans. Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parenthesis in front of the actual variable. (char)a will make 'a' function as a char. Converting an expression of a given type into another type is known as type-casting. We have already seen some ways to type cast:

Different types of types casting1. Implicit typecasting and2. Explicit typecasting

Implicit TypeCasting Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

short a=2000;int b;b=a;Here, the value of a has been promoted from short to int and we have not had to

specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:

class A {};

class B {

public: B (A a) {}

};

A a;B b=a;

42

Page 43: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Here, a implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter. Therefore implicit conversions from A to B are allowed.

Explicit Type Casting C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

short a=2000;int b;b = (int) a; // c-like cast notationb = int (a); // functional notation

The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:

// class type-casting#include <iostream>using namespace std;

class CDummy {

float i,j;};

class CAddition {

int x,y; public:

CAddition (int a, int b) {

x=a; y=b; }

int result() {

return x+y;}

};

int main () {

CDummy d; CAddition * padd; padd = (CAddition*) &d; cout << padd->result(); return 0;

43

Page 44: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

}The program declares a pointer to CAddition, but then it assigns to it a reference

to an object of another incompatible type using explicit type-casting:Traditional explicit type-casting allows to convert any pointer into any other

pointer type, independently of the types they point to. The subsequent call to member result will produce either a run-time error or a unexpected result.

Programs Based on Constructor, Destructor and OverloadingProgram-1Program to demonstrate Constructor with Default Arguments

#include <iostream.h>#include<conio.h>class real{

int integer_part;int fractional_part;

public :real(int, int);void print_data();

};real::real(int in, int fr=0) // Constructor with default argument{

integer_part = in;fractional_part = fr;

}void real::print_data(){

cout << "Number : " << integer_part << ".";cout << fractional_part << "\n";

}void main(void){ clrscr();

real A1(12);real A2(121,34);A1.print_data();A2.print_data();

}

Program-2Program to demonstrate Constructor overloading

#include <iostream.h>#include<conio.h>class real{

int integer_part;int fractional_part;

public :44

Page 45: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

real(){}real(int a){integer_part=a;fractional_part=a;}real(int a, int b){integer_part=a;fractional_part=b;}void sum(real,real);void print_data();

};void real::sum(real r1,real r2){

integer_part=r1.integer_part+r2.integer_part;fractional_part=r1.fractional_part+r2.fractional_part;

}void real::print_data(){

cout << "Number : " << integer_part << ".";cout << fractional_part << "\n";

}void main(void){

clrscr();real r1;real r2(12);real r3(121,34);r2.print_data();r3.print_data();r1.sum(r1,r2);r1.print_data();getch();

}

Program-3Program to demonstrate use of constructor

/* A Simple Constructor */#include <iostream.h>#include <string.h>#include<conio.h>class sample{

char itemname[20];int cost;public :

45

Page 46: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

sample(); // Constructor declarationvoid print_data();

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

Page 47: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

cin>>feet;cout<<"\nEnter Inches : ";cin>>inches;}friend void add(DM dm, DB db, int ch);

};void add(DM dm, DB db, int ch){if(ch==1){//Result in meter-centimeter

dm.centimeters=dm.centimeters+(db.feet*30)+(db.inches*2.4);while(dm.centimeters>=100){

dm.meters++;dm.centimeters=dm.centimeters-100;

}cout<<"\nMeter : "<<dm.meters;cout<<"\nCentimeters : "<<dm.centimeters;

}elseif(ch==2){//Result in feet-inches

db.inches=db.inches+(dm.centimeters+dm.meters*100)/2.4;

while(db.inches>=12){

db.feet++;db.inches=db.inches-12;

}cout<<"\nFeet : "<<db.feet;cout<<"\nInches : "<<db.inches;

}else

cout<<"\nWrong input!!!";}void main(){

DM dm;DB db;int ch;int ans=1;

do{

clrscr();dm.getdata();db.getdata();

47

Page 48: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

cout<<"\n1.Meter-Centimeter";cout<<"\n2.Feet-Inches";cout<<"\nEnter your choice : ";cin>>ch;add(dm,db,ch);cout<<"\nDo u want to continue?(1/0):";cin>>ans;

}while(ans==1);getch();}

Program-5Program to demonstrate Matrix Operation

#include<iostream.h>#include<conio.h>#include<stdlib.h>#include<process.h> const int true=1; const int false=0;class matrix{

int maxrow;int maxcol;int m[10][10];

public:matrix(){

maxrow=0;maxcol=0; }matrix(int row,int col){

maxrow=row;maxcol=col;

}void read();void show();void add(matrix a,matrix b);void sub(matrix a,matrix b);void mul(matrix a,matrix b);int eq1(matrix b);

};void matrix :: add(matrix a, matrix b){

int i,j;maxrow=a.maxrow;maxcol=a.maxcol;

if(a.maxrow!=b.maxrow ||a.maxcol!=b.maxcol){

48

Page 49: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

cout<<"\nInvalid order of matrix"; exit(0);} for(i=0;i<maxrow;i++) {

for(j=0;j<maxcol;j++)m[i][j]=a.m[i][j]+b.m[i][j];

}}void matrix :: sub(matrix a, matrix b){

int i,j;maxrow=a.maxrow;

maxcol=a.maxcol;if(a.maxrow!=b.maxrow ||a.maxcol!=b.maxcol){cout<<"\nInvalid order of matrix";exit(0);}for(i=0;i<maxrow;i++) {

for(j=0;j<maxcol;j++)m[i][j]=a.m[i][j]-b.m[i][j];

}}void matrix :: mul(matrix a, matrix b){

int i,j,k;maxrow=a.maxrow;

maxcol=a.maxcol;if(a.maxcol!=b.maxrow){ cout<<"\nInvalid order of matrix"; exit(0);}

for(i=0;i<maxrow;i++) {

for(j=0;j<maxcol;j++){m[i][j] =0;for(k=0;k<maxcol;k++)

m[i][j]=m[i][j]+a.m[i][k]*b.m[k][j];}

}}int matrix::eq1(matrix b){

49

Page 50: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

int i,j;for(i=0;i<maxrow;i++)

for(j=0;j<maxcol;j++)if(m[i][j]!=b.m[i][j])return 0;

return 1;}void matrix::read(){int i,j;for(i=0;i<maxrow;i++)

for(j=0;j<maxcol;j++){

cout<<"matrix["<<i<<","<<j<<"]=";cin>>m[i][j];

}}void matrix ::show(){

int i,j;for(i=0;i<maxrow;i++){

cout<<"\n";for(j=0;j<maxcol;j++)cout<<m[i][j]<<" ";

}}void main(){int m,n,p,q;clrscr();cout<<"\nEnter matrix A :";cout<<"\nEnter rows : ";cin>>m;cout<<"\nEnter cols : ";cin>>n;matrix a(m,n);a.read();cout<<"\nEnter matrix B : ";cout<<"\nEnter rows : ";cin>>p;cout<<"\nEnter cols : ";cin>>q;matrix b(p,q);b.read();

cout<<"\nmatrix A is : ";a.show();

50

Page 51: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

cout<<"\nmatrix B is : ";b.show();

matrix c(m,n);c.add(a,b);cout<<"\nC=A+B : ";c.show();matrix d(m,n);d.sub(a,b);cout<<"\nD=A-B : ";d.show();

matrix e(m,q);e.mul(a,b);cout<<"\nE=A*B : ";e.show();if(a.eq1(b))

cout<<"\nA = B ?-yes";else

cout<<"\nA = B ?-no";getch();}

Program-6Program to demonstrate overloading of different operators

# include<iostream.h># include<conio.h>class NUM{int a;public:

void getdata(){

cout<<"Enter value : " ;cin>>a;

}NUM operator +(NUM n){

NUM temp;temp.a=a+n.a;return (temp);

}NUM operator -(NUM n){

NUM temp;temp.a=a-n.a;return (temp);

51

Page 52: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

}NUM operator *(NUM n){

NUM temp;temp.a=a*n.a;return (temp);

}NUM operator /(NUM n){

NUM temp;temp.a=a/n.a;return (temp);

}void operator ++(){

a++;}void operator -(){

a=-a;}void disp(){

cout<<a;}

};void main(){

NUM n1,n2,n3;clrscr();n1.getdata();n2.getdata();

n3=n1+n2;cout<<"\nn1+n2 : ";n3.disp();

n3=n1-n2;cout<<"\nn1-n2 : ";n3.disp();

n3=n1*n2;cout<<"\nn1*n2 : ";n3.disp();

n3=n1/n2;cout<<"\nn1/n2 : ";n3.disp();

52

Page 53: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

++n1;cout<<"\n++n1 : ";n1.disp();-n2;cout<<"\n-n2 : ";n2.disp();getch();

}

Program-7Program to demonstrate overloading of ^ operator

#include<iostream.h>#include<conio.h>class pow{

int no;public:

pow(){ }

void getno();void dispno();pow operator^(pow);

};void pow::getno()

{cout<<"\nEnter number : ";cin>>no;

}void pow:: dispno()

{cout<<no;

}pow pow::operator^(pow p1)

{pow r;int i,sum=1;for(i=1;i<=p1.no;i++)

{sum*=no;

}r.no=sum;return(r);

}

void main(){

pow p1,p2,p3;53

Page 54: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

clrscr(); p1.getno(); p2.getno(); p3=p1^p2; cout<<"\nResult : "; p3.dispno(); getch();

}

Program-8Program to Demostrate overloading of operator +=

#include<iostream.h>#include<conio.h>class distance{

int feet;float inches;

public:distance()

{ feet=0; inches=0.0;

}distance(int ft,float in)

{feet=ft;inches=in;

}void getdist()

{cout<<"\nEnter feet:";cin>>feet;cout<<"\nEnter inches : ";cin>>inches;

}void showdist()

{cout<<"Feet : "<<feet<<"Inches : "<<inches;

}void operator +=(distance d2);

};

void distance::operator +=(distance d2){

feet+=d2.feet;inches+=d2.inches;while(inches>=12)

{inches=inches-12;feet++;

54

Page 55: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

}}

void main(){

distance d1,d2;clrscr();d1.getdist();d2.getdist();d1+=d2;cout<<"\nResult : ";d1.showdist();getch();

}Program-9Program to demonstrate multiple constructor or constructor overloading

#include<iostream.h>class Account{

int acc_no;float amount;char acc_type;public:Account(){}Account(int no,float bal,char type='S')

{acc_no=no;amount=bal;acc_type=type;

}void display()

{cout<<"\nAccount No. : "<<acc_no;cout<<"\nBalance : "<<amount;cout<<"\nAccount Type : "<<acc_type;

}};void main(){

Account a1,a2;int no;float bal;char type;cout<<"\nEnter Account Number, Balance and Account type";cin>>no>>bal>>type;a1=Account(no,bal,type);cout<<"\nEnter Account Number, Balance";cin>>no>>bal;a2=Account(no,bal);

55

Page 56: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

a1.display();a2.display();

} Program-10Program to demostrate increment and decrement Operator#include<iostream>using namespace std;

//Increment and decrement overloadingclass Inc {

private:int count ;

public:Inc() {

//Default constructorcount = 0 ;

}

Inc(int C) {// Constructor with Argumentcount = C ;

}

Inc operator ++ () {// Operator Function Definitionreturn Inc(++count);

}

Inc operator -- () {// Operator Function Definitionreturn Inc(--count);

}

void display(void) {cout << count << endl ;

}};

void main(void) { int a, b(4), c, d, e(1), f(4);

cout << "Before using the operator ++()\n";cout << "a = ";a.display();cout << "b = ";b.display();

++a;

56

Page 57: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

b++;

cout << "After using the operator ++()\n";cout << "a = ";a.display();cout << "b = ";b.display();

c = ++a;d = b++;

cout << "Result prefix (on a) and postfix (on b)\n";cout << "c = ";c.display();cout << "d = ";d.display();

cout << "Before using the operator --()\n";cout << "e = ";e.display();cout << "f = ";f.display();

--e;f--;

cout << "After using the operator --()\n";cout << "e = ";e.display();cout << "f = ";f.display();

}

Program-11Program to demostrate Binary operator overloading(+,!=,==)#include<iostream>using namespace std;

class Rational{

private:int num; // numeratorint den; // denominator

public:void show();Rational(int=1,int=1);void setnumden(int,int);Rational add(Rational object);Rational operator+(Rational object);

57

Page 58: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

bool operator==(Rational object);bool operator!=(Rational object);

};

void Rational::show() {

cout << num << "/" << den << "\n";}

Rational::Rational(int a,int b) {

setnumden(a,b);}

void Rational::setnumden(int x,int y) {

int temp,a,b;a = x;b = y;if(b > a)

{temp = b;b = a;a = temp;

}while(a != 0 && b != 0)

{if(a % b == 0)

break;temp = a % b;a = b;b = temp;

} num = x / b;

den = y / b;}

Rational Rational::add(Rational object) {

int new_num = num * object.den + den * object.num;int new_den = den * object.den;return Rational(new_num, new_den);

}

Rational Rational::operator+(Rational object) {

int new_num = num * object.den + den * object.num;int new_den = den * object.den;return Rational(new_num, new_den);

58

Page 59: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

}

bool Rational::operator==(Rational object) {

return (num == object.num && den == object.den);}

bool Rational::operator!=(Rational object) {

return (num != object.num || den != object.den);}

int main() {Rational obj1(1,4), obj2(210,840), result1;result1 = obj1.add(obj2);result1.show();

Rational obj3(1,3), obj4(33,99), result2;result2 = obj3 + obj4;result2.show();

Rational obj5(10,14), obj6(25,35), obj7(2,3), obj8(1,2);

if(obj5 == obj6) {

cout << "The two fractions are equal." << endl;}

if(obj7 != obj8) {

cout << "The two fractions are not equal." << endl;}

return 0;}

Program Based on Operator Overloading for String OperationProgram-12Program to demonstrate overloading of Relational operatorAns. /* Overloading Relational Operators */

#include <iostream.h>#include <string.h>#include<conio.h>/*----------------------Class definition-------------------------*/class string{

char *s;int length;

public:

59

Page 60: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

string();string(char*);

// Overloaded Relational operator '=='int operator == (string);// Overloded '+' operatorfriend string operator + (string, string);

void show();};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);

}// Overloaded '==' relational operator as a member functionint string::operator == (string x){

int flag = 0;if (length == x.length){

flag = 1;for (int i=0; i<length; i++){

if (s[i] != x.s[i]){

flag = 0;break;

}}

}return flag;

}void string::show(){

cout << s << "\t(Length = " << length << ")\n";}/*----------------------Definition ends here---------------------*/// Overloded '+' (concatenation) operator as a friend functionstring operator + (string x, string y){

60

Page 61: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

string temp;temp.length = x.length + y.length;temp.s = new char[temp.length + 1];strcpy(temp.s, x.s);strcat(temp.s, y.s);return temp;

}void main(void){

string s1("Good "),s2("Morning"),s3, s4("Morning");clrscr();s3 = s1 + s2; // concatenationcout << "The result of concatenation :\n";s3.show();

cout << "\nThe result of comparison of s1 & s2 :\n";cout << (s1 == s2);cout << "\nThe result of comparison of s2 & s4 :\n";cout << (s2 == s4);getch();

}

Program from the Board PapersProgram-13Define 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

Page 62: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

Same program with class and object approachAns.

#include <iostream.h>#include <conio.h>class Area

{

float CalArea(int rad){

float area;area = 3.14 *rad *rad ;return (area);

}

int CalArea(int len , int bre){

int area;area = len , bre ;return (area);

}};

void main(){ Area a1; float arcir = a1.CalArea (4); int arrect = a1.CalArea(5,6); cout << “\n Area of circle = “<<arcir; cout<< “\nArea of rectangle =”<<arrect;getch();}

Program-14Overload increment operator for class point having data member as x and y co-ordinateAns.

Class Point{ private :int xinc , yinc ;public:Point operator++ ( ){Point temp;temp.x= ++xinc;temp.y= ++yinc;return(temp);}

void disp()62

Page 63: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

{cout<<”\n X =”<<x;;cout<<”\n Y =”<<y;}

Point(){xinc=0;yinc=0;}};void main(){Point p1,p2;p1++;++p2;p1.disp();p2.disp();getch();}

Program-15Q.Write a program to find sum of nos. between 1 to n using constructor where value of ‘n’ will be passed to the constructorAns.

class sum_of_series{

int n;int sum;

public :void getRange(int x)

{n = x;sum = 0 ;

}void calculateSeries()

{for (int i=1;i<= n ; i++)

{sum = sum + i;

}}

void display(){

cout<<”\n sum of “<< n <<” numbers = “<<sum;}

};void main()

63

Page 64: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

{sum_of_series ss1;ss1.getRange(10);ss1.calculateSeries();ss1.display();getch();

}

Program-16Overload the unary ‘-’ operator so that when it is used with an object the value of numeric data member of the -class will be negatedAns.

Class Minus{ private :int num;public:void getData(int x)

{num = x;

}

void operator -( ){x = -x;}

void display(){cout<<”\n Number =”<<num;}

};void main(){Minus m1 , m2 ;m1.getData(10);-m1; //activate operator –() functionm1.display(); m2.getData(200);-m2; //activate operator –() functionm2.display();getch();}

Board Question Chapter WiseWinter 2007

a. Define following terms64

Page 65: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

(i) Default constructor(ii) Parameterized constructor

Ans.Refer Q.No.b. What is destructor ? How many destructors can be defined in a single class ?Ans.Refer Q.No.c. What is need of operator over loadingAns.Refer Q.No.

d. Define two functions with same name one returns area of circle whereas another returns area of rectangle. Test these functions.

Ans.Refer Q.No.

e. Overload increment operator for class point having data member as x and y co-ordinate

Ans.Refer Q.No.

f. What do you mean by default argument ? Illustrate concept of constructor with default argument, with suitable example.

Ans.Refer Q.No.

Summer 2008a. Give any 4 characteristics of constructorAns.Refer Q.No.

b. Define parameterized constructor with its syntaxAns.Refer Q.No.

c. What are the ways of constructor calling in main program? Give its syntax Ans.Refer Q.No.

Winter 2008a. Describe of process operator overloading with example.Ans.Refer Q.No.

b. State the use of default parameters in constructor with suitable example.Ans.Refer Q.No.

Summer 2009a. Write two advantages of using constructor.Ans.Refer Q.No.b. Write syntax for the following

(i) Type casting(ii) Parameterized constructor

Ans.Refer Q.No.c. Write any four operators which can be overloaded.Ans.Refer Q.No.

65

Page 66: Constructor and Destructor - Yolakavediasir.yolasite.com/resources/Chapter-3... · A constructor is special member function whose task is to initialize all the private data members

Prof.Manoj S.Kavedia (9860174297)([email protected])

d. Define early binding and late binding.Ans.Refer Q.No.e. What are the rules for writing destruction function and when they are invoked ?Ans.Refer Q.No.f. Write 4 rules for overloading operator.Ans.Refer Q.No.

Winter 2009a. What is constructor? Is it mandatory to use constructors in a class?Ans.Refer Q.No.

b. List any four properties of constructor function.Ans.Refer Q.No.

c. Explain parameterized constructor with exampleAns.Refer Q.No.

d. Write rules for overloading operatorsAns.Refer Q.No.

Summer 2010a. Define Terms

(i) Default constructor(ii) Parameterized constructor

Ans.Refer Q.No.

b. List the operators which cannot be overloaded.Ans.Refer Q.No.

c. What is function overloadingAns.Refer Q.No.

d. Write a program to find sum of nos. between 1 to n using constructor where value of ‘n’ will be passed to the constructor

Ans.Refer Q.No.

e. Overload the unary-operator so that when it is used with an object the value of numeric data member of the-class will be negated

Ans.Refer Q.No.

66