Chapter – 5. CONSTRUCTORS & DESTRUCTORS

Ans:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class TravelPlan
{ long PlanCode;
char Place[21];
int Number_of_travellers,Number_of_buses;
public: TravelPlan( )
{
PlanCode=1001;
strcpy(Place,"Agra");
Number_of_travellers=5;
Number_of_buses=1;
}
void NewPlan( )
{
cout<<"\nEnter the Plan Code: ";
cin>>PlanCode;
cout<<"\nEnter the Place to Travel: ";
gets(Place);
cout<<"\nEnter the Number of Travellers: ";
cin>>Number_of_travellers;
if(Number_of_travellers>=40) Number_of_buses=3;
else if(Number_of_travellers>=20) Number_of_buses=2;
else
Number_of_buses=1;
}
void ShowPlan( )
{
cout<<"\nThe Plan Code: "<<PlanCode;
cout<<"\nThe Place of Travel: "<<Place;
cout<<"\nNumber of Travellers: "<<Number_of_travellers;
cout<<"\nNumber of Buses: "<<Number_of_buses;
}
};
void main( )
{
clrscr( );
TravelPlan T;
T.NewPlan( );
T.ShowPlan( );
getch();
}

OUTSIDE DELHI 2005

1.a. Differentiate between a default constructer and copy constructer, giving suitable examples of each.

Ans: A default constructor also called as non-parameterized constructor will take no argument and initialize the object with the predefined values in that constructor, Where as a copy constructor will take an already created object of that class and stores that object values into the newly created object of that class. A copy constructor takes a reference to an object of the same class as an argument.

2.b. Answer the following questions (i)and (ii) after going through the following class.

class Exam
{
int Marks;
char Subject[20];
public: Exam() //Function 1
{
strcpy(Subject,”Computer”);
Marks=0;
}
Exam(char S[]) //Function 2
{
strcpy(Subject,S);
Marks=0;
}
Exam(int M) //Function 3
{
strcpy(Subject,”Computer”);
Marks=M;
}
Exam(char S[],int M) //Function 4
{
Strcpy(Subject,P);
Marks=M;
}
};

(i) Write statements in C++ that would execute Function 3 and Function 4 of class Exam.
(let char name[20];
int X=60; strcpy(name,”COMPUTERSCIENCE”);
are declared in the program)

(i) Exam A(X); //Will execute Funciton 3
(ii) Exam B(name,X); //Will execute Function 4

(ii) Which feature Object Oriented Programming is demonstrated using Function 1, Function 2, Function 3 and Function 4 in the above class text?

Ans: Function overloading (here it is constructor overloading).

2.c. Define a class Travel in C++ with the following descriptions: