Free Essay

C++ Solution

In: Computers and Technology

Submitted By kabinshrestha
Words 27162
Pages 109
1. Explain the following. (i) Conversion from Class to Basic Type. (ii) File Pointers. (iii) Function Prototyping. (iv) Overload resolution. (i) Conversion from Class to Basic Type: We know that conversion from a basic to class type can be easily done with the help of constructors. The conversion from class to basic type is indeed not that easy as it cannot be done using constructors. for this conversion we need to define an overloaded casting operator. This is usually referred to as a conversion function. The syntax for this is as follows:

operator typename(){….}

The above function shall convert a class type data to typename.
A conversion function must follow the following 3 rules:
a. It cannot have a return type
b. It has to be declared inside a class.
c. It cannot have any arguments.

(ii)File pointers: we need to have file pointers viz. input pointer and output pointer. File pointers are required in order to navigate through the file while reading or writing. There are certain default actions of the input and the output pointer. When we open a file in read only mode, the input pointer is by default set at the beginning. When we open a file in write only mode, the existing contents are deleted and the file pointer is attached in the beginning. C++ also provides us with the facility to control the file pointer by ourselves. For this, the following functions are supported by stream classes: seekg(), seekp(), tellg(), tellp().

(iii) Function prototyping is used to describe the details of the function. It tells the compiler about the number of arguments, the type of arguments, and the type of the return values. It some what provides the compiler with a template that is used when declaring and defining a function. When a function is invoked, the compiler carries out the matching process in which it matches the declaration of the function with the arguments passed and the return type. In C++, function prototype was made compulsory but ANSI C makes it optional. The syntax is as follows:

type function-name(argument-list);

example: int func(int a, int b, int c);

(iv)Overload resolution: When we overload a function, the function prototypes are matched by the compiler. The best match is found using the following steps.
a. The compiler first matches that prototype which has the exactly same types of actual arguments. b. If an exact match is not found by the first resolution, the integral promotions to the actual arguments are used like char to int, float to double.
c. When both the above methods fail, the built in conversions to the actual arguments are used like long square (long n).
d. If all the above steps do not help the compiler find a unique match, then the compiler uses the user defined convergence, in combination with integral promotions and built in conversions. 2 Write a C++ program that prints
1 1.0000e+00 1.000
2 5.0000e-01 1.500
3 3.3333e-01 1.833
Ans: #include<iostream.h>
#include<iomanip.h>
void main()
{
float x,y,z; x=1.0000e+00; y=5.0000e-01; z=3.3333e-01; cout.setf(ios::showpoint); cout.precision(3); cout.setf(ios::fixed,ios::floatfield); cout<<x<<'\n'; cout<<y<<'\n'; cout<<z<<'\n'; }
3. What are friend functions? Explain there characteristics with a suitable example.
Ans: We generally have a belief that a non member function cannot access the private data member of the class. But this is made possible using a friend function. A friend function is that which does not belong to the class still has complete access to the private data members of the class. We simply need to declare the function inside the class using the keyword “friend”. The syntax for declaring the friend function is as follows: class demo
{
public: friend void func (void);
}
The characteristics of a friend function are as follows.
• It can be declared both in the private and the public part of the class without altering the meaning. • It is not called using the object of the class.
• To access the data members of the class, it needs to use the object name, the dot operator and the data member’s name. example obj.xyz
• It is invoked like a normal function.
• It does not belong to the class

An example program is as follows:
|#include<iostream.h> |void max(two s,one t) |
|class one; |{ |
|class two |if(s.a>=t.b) |
|{ |cout<<s.a; |
|int a; |else |
|public: |cout<<t.b; |
|void setvalue(int n){a=n;} |} |
|friend void max(two,one); |int main() |
|}; |{ |
|class one |one obj1; |
|{ |obj1.setvalue(5); |
|int b; |two obj2; |
|public: |obj2.setvalue(10); |
|void setvalue(int n){b=n;} |max(obj2,obj1); |
|friend void max(two,one); |return 0; |
|}; |} |

4. Write a program to overload the operator ‘+’ for complex numbers. (7)
Ans: To perform complex number addition using operator overloading.
|# include <iostream.h> |Complex complex::Operator+(Complex(2)) |
|# include <conio.h> |{ |
|class complex { |complex temp; |
|float r, i; |temp.r=r+c2.r; |
|public: |temp.i=I=c2.i; |
|complex() |return(temp); |
|{ |} |
|r=i=0; |void main() |
|} |{ |
|void getdata() |clrscr(); |
|{ |complex c1, c2, c3; |
|cout<<”R.P”; |cout<<”Enter 2 complex no: “<<endl; |
|cin>>r; |cl.getdta(); |
|cout<<”I.P”; |c2.getdata(); |
|cin>>i; |c3=c1+c2; |
|} |c3.outdata (“The result is :”); |
|void outdata (char*msg) |getch(); |
|{ |} |
|cout<<endl<,msg; |OUTPUT |
|cout<<”(“<<r; |Enter 2 complex no: R.P: 2 I.P: 2 R.p: 2 I.P:2 |
|cout<<”+j” <<i<<”)”; |The result is: 4+j4 |
|} |RESULT |
|Complex operator+(Complex); |Thus the complex number addition has been done using operator |
|}; |overloading |

5. Write a complete C++ program to do the following :
(i) ‘Student’ is a base class, having two data members: entryno and name; entryno is integer and name of 20 characters long. The value of entryno is 1 for Science student and 2 for Arts student, otherwise it is an error.
(ii) ‘Science’ and ‘Arts’ are two derived classes, having respectively data items marks for Physics, Chemistry, Mathematics and marks for English, History, Economics.
(iii) Read appropriate data from the screen for 3 science and 2 arts students.
(iv) Display entryno, name, marks for science students first and then for arts students.
Ans:
|#include<iostream.h> |class arts:public student |
|class student |{ |
|{ |int ehe[3]; |
|protected: |public: |
|int entryno; |void getdata() |
|char name[20]; |{ |
|public: |student::getdata(); |
|void getdata() |cout<<"Enter marks for English,History and Economics"<<endl; |
|{ |for(int j=0;j<3;j++) |
|cout<<"enter name of the student"<<endl; |{ |
|cin>>name; |cin>>ehe[j]; |
|} |} |
|void display() |} |
|{ |void display() |
|cout<<"Name of the student is"<<name<<endl; |{ |
|} |entryno=2; |
|}; |cout<<"entry no for Arts student is"<<entryno<<endl;; |
|class science:public student |student::display(); |
|{ |cout<<"Marks in English,History and Economics are"<<endl; |
|int pcm[3]; |for(int j=0;j<3;j++) |
|public: |{ |
|void getdata() |cout<<ehe[j]<<endl;; |
|{ |} |
|student::getdata(); |} |
|cout<<"Enter marks for Physics,Chemistry and Mathematics"<<endl; |}; |
|for(int j=0;j<3;j++) |void main() |
|{ |{ |
|cin>>pcm[j]; |science s1[3]; |
|} |arts a1[3]; |
|} |int i,j,k,l; |
|void display() |cout<<"Entry for Science students"<<endl; |
|{ |for(i=0;i<3;i++) |
|entryno=1; |{ |
|cout<<"entry no for Science student is"<<entryno<<endl; |s1[i].getdata(); |
|student::display(); |} |
|cout<<"Marks in Physics,Chemistry and Mathematics are"<<endl; |cout<<"Details of three Science students are"<<endl; |
|for(int j=0;j<3;j++) |for(j=0;j<3;j++) |
|{ |{ |
|cout<<pcm[j]<<endl;; |s1[j].display(); |
|} |} |
|} |cout<<"Entry for Arts students"<<endl; |
|}; |for(k=0;k<3;k++) |
| |{ |
| |a1[k].getdata(); |
| |} |
| |cout<<"Details of three Arts students are"<<endl; |
| |for(l=0;l<3;l++) |
| |{ |
| |a1[l].display(); |
| |} |
| |} |

6. An electricity board charges the following rates to domestic users to discourage large consumption of energy :
For the first 100 units - 50 P per unit
Beyond 300 units - 60 P per unit
If the total cost is more than Rs.250.00 then an additional surcharge of 15% is added on the difference. Define a class Electricity in which the function Bill computes the cost. Define a derived class More_Electricity and override Bill to add the surcharge. (8)
Ans:
|#include<iostream.h> |class more_electricity:public electricity |
|class electricity |{ |
|{ |float surcharge,diff,total_cost; |
|protected: |public: |
|float unit; |void bill() |
|float cost; |{ |
|public: |electricity::bill(); |
|void bill() |if(cost>250.00) |
|{ |{ |
|cout<<"\n enter the no. of units"<<endl; |diff=cost-250; |
|cin>>unit; |surcharge=diff*0.15; |
|if(unit<=100) |total_cost=cost+surcharge; |
|{ |cout<<" Bill amount with surcharge is Rs"<<total_cost; |
|cost=0.50*unit; |} |
|cout<<"cost up to 100 unit is Rs."<<cost<<endl; |else |
|} |{ |
|else |cout<<"Bill amout is Rs."<<cost; |
|{ |}}}; |
|if(unit>300) |void main() |
|{ |{ |
|cost=0.60*unit; |more_electricity me; |
|cout<<"Beyond 300 units is Rs"<<cost; |me.bill(); |
|} |} |
|} | |
|} | |
|}; | |

Q.7 Write a program to open a file in C++ “Hello.dat” and write
“This is only a test”
“Nothing can go wrong”
“All things are fine…” into the file. Read the file and display the contents. (6)
Ans:
|#include<iostream.h> |ifstream fin; |
|#include<fstream.h> |fin.open("Hello.dat"); |
|void main() |cout<<"Contents of the Hello.dat file\n"; |
|{ |while(fin) |
|ofstream fout; |{ |
|fout.open("Hello.dat"); |fin.getline(line,N); |
|fout<<"This is only a test\n"; |cout<<line; |
|fout<<"Nothing can go wrong\n"; |} |
|fout<<"All things are fine....\n"; |fin.close();} |
|fout.close(); | |
|const int N=100; | |
|char line[N]; | |

8. Develop a program in C++ to create a database of the following items of the derived class. Name of the patient, sex, age, ward number, bed number, nature of illness, date of admission. Design a base class consisting of data members : name of the patient, sex and age ; and another base class consisting of the data members : bed number and nature of the illness. The derived class consists of the data member ,date of admission. Program should carry out the following methods
(i) Add a new entry.
(ii) List the complete record.
Ans:.
|#include<conio.h> |class C:public A,public B{ |
|#include<iostream.h> |int date_admission; |
|class A{ |public: |
|public: |void get_data(); |
|char name[20]; |void disp_data(); |
|char sex[10]; |void record(); |
|int age; |}; |
|void get_data(); |void C::get_data(){ |
|void disp_data(); |A::get_data(); |
|}; |B::get_data(); |
|void A::get_data(){ |cout<<endl<<"Enter Data of Admission:-> "; |
|cout<<"enter d name:"; |cin>>date_admission; |
|cin>>name; |} |
|cout<<"enter d age:"; |void C::disp_data(){ |
|cin>>age; |A::disp_data(); |
|cout<<"enter d sex:"; |B::disp_data(); |
|cin>>sex;} |cout<<endl<<"Date of Admission\t"<<date_admission; |
|void A::disp_data(){ |} |
|cout<<"name:"<<name<<'\n'; |void main(){ |
|cout<<"age:"<<age<<'\n'; |clrscr(); C c1; |
|cout<<"sex:"<<sex<<'\n';} |cout<<endl<<"Adding a new record to database\n"; |
|class B{ |getch(); |
|public: |c1.get_data(); |
|int bed_number; |cout<<endl<<"Displaying the added record to database\n"; |
|char nature_illness[40]; |c1.disp_data(); |
|void get_data(); |getch(); |
|void disp_data(); |} |
|}; | |
|void B::get_data(){ | |
|cout<<"enter d bed_number:"; | |
|cin>>bed_number; | |
|cout<<"enter d nature_illness:"; | |
|cin>>nature_illness; | |
|} | |
|void B::disp_data(){ | |
|cout<<"bed_number:"<<bed_number<<'\n'; | |
|cout<<"nature_illness:"<<nature_illness<<'\n'; | |
|} | |

Q.9 How many times is the copy constructor called in the following code? (4)
Apple func(Apple u)
{
Apple w=v;
Return w;
}
void main()
{
Apple x;
Apple y = func (x);
Apple z = func (y);
}
Ans: 2 times
10 Create a class Time that has separate int member data for hours, minutes and seconds. One constructor should initialize this data to zero and another constructor initialize it to fixed values. Write member function to display time in 12 hour as well as 24 hour format. The final member function should add two objects of class Time. A main() program should create three objects of class time, of which two are initialized to specific values and third object initialized to zero. Then it should add the two initialized values together, leaving the result in the third. Finally it should display the value of all three objects with appropriate headings.
Ans:
|#include<iostream.h> |time12::time12(time24 t24) |
|#include<string.h> |{ |
|class time24 |int hrs24=hours; |
|{ |bool pm=hours<12 ? false:true; |
|int hours,minutes,seconds; |int min=seconds<30 ? minutes:minutes+1; |
|public: |if(min==60) |
|time24() |{ |
|{ |min=0; |
|hours=minutes=seconds=0; |++hrs24; |
|} |if(hrs24==12 || hrs24==24) |
|time24(int h,int m,int s) |pm=(pm==true)? false:true; |
|{ |} |
|hours=h; |int hrs12=(hrs24<13) ? hrs24 : hrs24-12; |
|minutes=m; |if(hrs12==0) |
|seconds=s; |{ |
|} |hrs12=12; |
|void display() |pm=false; |
|{ |} |
|if(hours<10) |return time12(pm,hrs12,min); |
|cout<<'0'; |} |
|cout<<hours<<":"; |int main() |
|if(minutes<10) |{ |
|cout<<'0'; |int h1,m1,s1; |
|cout<<minutes<<":"; |while(true) |
|if(seconds<10) |{ |
|cout<<'0'; |cout<<"enter 24-hour time:\n"; |
|cout<<seconds; |cout<<"Hours(0-23):"; |
|} |cin>>h1; |
|}; |if(h1>23) |
|class time12 |return(1); |
|{ |cout<<"Minutes:"; |
|bool pm; |cin>>m1; |
|int hour,minute; |cout<<"Seconds:"; |
|public: |cin>>s1; |
|time12() |time24 t24(h1,m1,s1); |
|{ |cout<<"you entered:"; |
|pm=true; |t24.display(); |
|14 |cout<<endl; |
|Code: AC11 Subject: OBJECT ORIENTED PROGRAMMING |time12 t12=t24; |
|hour=minute=0; |cout<<"\n12-hour time:"; |
|} |t12.display(); |
|time12(bool ap,int h,int m) |cout<<endl; |
|{ |} |
|pm=ap; |return 0; |
|hour=h; |} |
|minute=m; | |
|} | |
|time12(time 24); | |
|void display() | |
|{ | |
|cout<<hour<<":"; | |
|if(minute<10) | |
|cout<<'0'; | |
|cout<<minute<<" "; | |
|char *am_pm=pm ? "p.m." : "a.m."; | |
|cout<<am_pm; | |
|} | |
|}; | |

11. In the following output, the following flag constants are used with the stream member function setf. What effect does each have
(i) ios::fixed
(ii) ios::scientific
(iii) ios::showpoint
(iv) ios::showpos
(v) ios::right
(vi) ios::left (6)
Ans: A two argument version of setf() is used to set flag which is a member of a group of flags. The second argument specifies the group and is a bitwise OR of all the flags in the group. The setfO, a member function of the ios class, can provide answers to these and other formatting questions. The setfO (setf stands for set flags) function can be us follows: cout.setf(argl,arg2) The argl is one of the formatting flags defined in the class ios. The formatting flag Spi the format action required for the output. Another ios constant, arg2, known as bi specifies the group to which the formatting flag belongs. There are three bit and each has a group of format flags which are mutually exclusive cout.setf(ios::1eft, ios::adjustfied); cout.setf(ios::scientific, ios::floatfield);
Note that the first argument should be one of the group members of the second argument.
The setf() can be used with the flag ios::showpoint as a single argument to achieve this form of output. For example cout.setf(ios::showpoint); Would cause cout to display trailing zeros and trailing decimal point. Similarly, a plus sign can be printed a positive number using the following statement: cout.setf(ios::showpos);set to selection selection ios::ingroup Meaning ios::left ios::adjustfield left alignment ios::right ios::adjustfield right alignment ios::fixed ios::floatfield fixed form of floating point ios::scientific ios::floatfield force exponential format ios::showpoint // Always show a point ios::showpos // If positive still show sign

12. Define a class Distance with feet and inch and with a print function to print the distance. Write a non-member function max which returns the larger of two distance objects, which are arguments. Write a main program that accepts two distance objects from the user, compare them and display the larger.
Ans:
|#include<iostream.h> |friend void maxdist(distance d1, distance d2) |
|class distance |{ |
|{ |d1.feet=d1.feet+ d1.inches/12; |
|int feet; |d2.feet=d2.feet+ d2.inches/12; |
|float inches; |if(d1.feet>d2.feet) |
|public: |{ |
|distance() |cout<<"first distance is greater"; |
|{ |} |
|feet=0; |else |
|inches=0.0; |{ |
|} |cout<<"second distance is greater"; |
|void getdist() |} |
|{ |} |
|cout<<"Enter feet:"<<endl; |}; |
|cin>>feet; |void main() |
|cout<<"Enter inches:"<<endl; |{ |
|cin>>inches; |distance d3,d4; |
|} |d3.getdist(); |
|void showdist() |d3.showdist(); |
|{ |d4.getdist(); |
|cout<<feet<<endl<<inches<<endl; |d4.showdist(); |
|} |maxdist(d3,d4); |
| |} |

a. Define the class Person which has name (char*) and age (int). Define the following constructors
a. default
b. with name as argument (assume age is 18)
c. with name and age as argument
Also define the copy constructor.
Ans:
|#include<iostream.h> |person(person &p) |
|#include<string.h> |{ |
|class person |strcpy(name,p.name); |
|{ |age=p.age; |
|char *name; |} |
|int age; |void disp() |
|public: |{ |
|person() |cout<<"name is"<<name; |
|{ |cout<<"age is"<<age; |
|name=NULL; |} |
|//strcpy(name,NULL); |}; |
|age=0; |void main() |
|} |{ |
|person(char *n) |person p1("ram"),p2("sita",20),p3=p2; |
|{ |cout<<"hello"; |
|strcpy(name,n); |p1.disp(); |
|age=18; |p2.disp(); |
|} |p3.disp(); |
|person(char *n1,int a) |} |
|{ | |
|strcpy(name,n1); | |
|age=a; | |
|} | |

b. Using the class above, define two subclasses Student and Professor. Student subclass displays the name and CGPA (grade points in float) and Professor subclass displays the name and number of publications (int). Write a main program using polymorphism to display the data of one student and one professor. (7)
Ans:
|#include<iostream.h> |class professor:public person |
|class person |{ |
|{ |int numpubs; |
|protected: |public: |
|char name[40]; |void getdata() |
|public: |{ |
|void getname() |person::getname(); |
|{ |cout<<"enter number of professor's publication:"; |
|cout<<"Enter name:"; |cin>>numpubs; |
|cin>>name; |} |
|} |bool outstanding() |
|void disp() |{ |
|{ |return(numpubs>100) ? true:false; |
|cout<<"Name is:"<<name<<endl; |} |
|} |}; |
|virtual void getdata()=0; |void main() |
|virtual bool outstanding()=0; |{ |
|}; |person *perptr[10]; |
|class student:public person |int n=0; |
|{ |char choice; |
|float gpa; |do |
|public: |{ |
|void getdata() |cout<<" Enter student or professor(s/p):"; |
|{ |cin>>choice; |
|person::getname(); |if(choice=='s') |
|cout<<"Enter student's GPA:"; |perptr[n]=new student; |
|cin>>gpa; |else |
|} |perptr[n]=new professor; |
|bool outstanding() |perptr[n++]->getdata(); |
|{ |cout<<"enter another(y/n)?"; |
|return(gpa>3.5) ? true:false; |cin>>choice; |
|} |}while (choice=='y'); |
|}; |for(int j=0;j<n;j++) |
| |{ |
| |perptr[j]->disp(); |
| |if(perptr[j]->outstanding()) |
| |cout<<"this person is outstanding\n"; |
| |} |
| |} |

13. Answer briefly :
(i) What happens in a while loop if the control condition is false initially ?
(ii) What is wrong with the following loop while (n <= 100)
Sum += n*n;
(iii) What is wrong with the following program int main( )
{
const double PI; int n;
PI = 3.14159265358979; n = 22;
}
(iv) When a multidimensional array is passed to a function, why does C++ require all but the first dimension to be specified in parameter list?
(v) Why can’t ** be overloaded as an exponentiation operator?
(vi) How many constructors can a class have, and how should they be distinguished.
Ans:
i) If the condition in while loop initially false the loop does not enter into the statements inside the loop and terminates initially. ii) In the given statement of while loop n is not initialized. Although there is no initialization expression, the loop variable n must be initialized before the loop begins. iii) The given program code is wrong as const declared PI must be initialized at the time of declaration. Whereas initialization of int n is correct the correct code is int main()
{
const double PI=3.1459265358979; int n=22;} iv) Multidimensional array is an array of arrays the function first take the argument as an array of parameter first. It does not need to know how many values in parameter there are, but it does need to know how big each parameter element is, so it can calculate where particular element is. So we must tell it the size of each element but not how many there are.
v) Only existing operator symbols may be overloaded. New symbols, such as ** for exponentiation, cannot be defined. vi) A class can have Default constructor, constructor with an argument, constructor with two argument and copy constructor.

Describe, in brief, the steps involved in object oriented analysis. (6)
Ans: The steps involved in object oriented analysis.
Object-oriented analysis provides us with a simple, yet powerful, mechanism for identifying objects, the building block of the software to be developed. The analysis is basically concerned with the decomposition of a problem into its component parts and establishing a logical model to describe the system functions.
The object-oriented analysis (OOA) approach consists of the following steps:
1. Understanding the problem.
2. Drawing the specifications of requirements of the user and the software.
3. Identifying the objects and their attributes.
4. Identifying the services that each object is expected to provide (interface).
5. Establishing inter-connections (collaborations) between the objects in terms of services
[pic]
The first step in the analysis process is to understand the problem of the user. The problem statement should be refined and redefined in terms of computer system engineering that could suggest a computer-based solution. The problem statement should be stated, as far as possible, in a single, grammatically correct sentence. This will enable the software engineers to have a highly focused attention on the solution of the problem. The problem statement provides the basis for drawing the requirements specification of both the user and the software.

Requirements Specification
Once the problem is clearly defined, the next step is to understand what the proposed. System is required to do. It is important at this stage to generate a list of user requirement A clear understanding should exist between the user and the developer of what is require Based on the user requirements, the specifications for the software should be drawn. Developer should state clearly What outputs are required? What processes are involved to produce these outputs? What inputs are necessary? What resources are required? These specifications often serve as a reference to test the final product for its performance the intended tasks.

Identification of Objects
Objects can often be identified in terms of the real-world objects as well as the abstra~ objects. Therefore, the best place to look for objects is the application itself. The applicationmay be analyzed by using one of the following two approaches:
1.Data flow diagrams (DFD)
2.Textual analysis (TA)
Identification of Services
Once the objects in the solution space have been identified, the next step is to identify set services that each object should offer. Services are identified by examining all the verbs are verb phrases in the problem description statement. Doing verbs and compare verbs usually give rise to services (which we call as functions C++). Being verbs indicate the existence of the classification structure while having verbs' rise to the composition structures.
Establishing interconnection
This step identifies the services that objects provide and receive. We may use an information flow diagram(IED) or an entity-relationship (ER) diagram to enlist this information.

14. What are the two methods of opening a file? Explain with examples. What is the difference between the two methods? (10)
Ans:
For opening a file, we first create a file stream which we can link to the file name. we can define a file stream using 3 classes namely ifstream, ofstream and fstream that are all contained in the header file fstream. Which class to use shall depend upon the mode in which we want to open the file viz, read or write. There are 2 modes to open a file.
• Using the constructor function of the class
• Using the member function “open()” of the class.
When using the first method that is constructor function of the class, we initialize the file stream object by file name. for example the following statement opens a file named “results” for input. ifstream infile (“results”);
When using the second method of function “open()”, multiple files can be opened that use the same stream object for example when we wish to process a number of files in sequential manner, we shall create a single stream object and use it to open each file in turn. The syntax is as follows: file-stream-class stream-object; stream-object.open(“filename”); The basic difference between the two methods is that the constructor function of the class is used when we wish to open just one file in the stream. The open function is used when we wish to open multiple files using one stream.

15. What is containership? How does it differ from inheritance? (4)
Ans: Inheritance, one of the major features of OOP, is to derive certain properties of the base class in the derived class. A derived class can make use of all the public data members of its base classes.
Containership is different from Inheritance. When one class is defined inside another class, it is known as containership or nesting. We can thus imply that one object can be a collection of many different objects. Both the concepts i.e. inheritance and containership have a vast difference. Creating an object that contains many objects is different from creating an independent object. First the member objects are created in the order in which their constructors occur in the body. Then the constructor of the main body is executed. An initialization list of the nested class is provided in the constructor.
Example:
class alpha{....}; class beta{....}; class gamma
{
alpha a; beta b; public: gamma(arglist): a(arglist1), b(arglist2) {
//constructor body
}};

16. How do the properties of following two derived classes differ?
(i) class X : public A{//..}
(ii) class Y : private A{//..} (5)
Ans: The properties of the following two derived class differ:-
(i) class X:public A{//..}
In this class A is publicly derived from class X. the keyword public specifies that objects of derived class are able to access public member function of the base class.
i) class Y:private A{//..}
In this class A is privately derived from class Y. the keyword private specifies that objects of derived class cannot access public member function of the base class. Since object can never access private members of a class.

17. What is dynamic initialization of objects? Why is it needed? How is it accomplished in C++? Illustrate. (8)
Ans: Dynamic initialization of objects means to provide the initial values to an object at run time. Using dynamic initialization of objects we can provide different initialization formats of data for an object at run time. We can use various data types like int, float or char depending upon our need for the same object created. This provides the flexibility of using different format of data at run time depending upon the situation. It can be accomplished using the concept of constructor overloading. For example:
#include<iostream.h>
class loan
{ long principle; int year; float rate; public: loan(){} loan(long p,int y,float r=0.15); loan(long p,int y,int r);
};
This class uses three overloaded constructors. The parameter values to these constructors are provided at run time. One can input in any of the form to create object of this class.

18. List at least three C++ operators which cannot be overloaded. (3)
Ans: The operators ::, .*, . and ?: cannot be overloaded.

19. What is multiple inheritance? Discuss the syntax and rules of multiple inheritance in C++. How can you pass parameters to the constructors of base classes in multiple inheritance? Explain with suitable example. (12)
Ans: C++ provides us with a very advantageous feature of multiple inheritance in which a derived class can inherit the properties of more than one base class. The syntax for a derived class having multiple base classes is as follows:
Class D: public visibility base1, public visibility base2
{
Body of D;
}
Visibility may be either ‘public’ or ‘private’.
In case of multiple inheritance, the base classes are constructed in the order in which they appear in the declaration of the derived class. However the constructors for virtual base classes are invoked before any non-virtual base classes. If there are multiple virtual base classes, they are invoked in the order in which they are declared. An example program illustrates the statement.
|#include<iostream.h> |class P: public N, public M |
|class M |{ int p,r; |
|{ |public: |
|protected: |P(int a,int b,int c, int d):M(a),N(b) |
|int m; |{ |
|public: |p=c; |
|M(int x) |r=d; |
|{ |cout<< “P initialized\n”; |
|m=x; |} |
|cout<< “M initialized\n”; |}; |
|} |void main() |
|}; |{ |
|class N |P p(10,20,30,40); |
|{ |} |
|protected: |Output of the program will be: |
|int n; |N initialized |
|public: |M initialized |
|N(int y) |P initialized |
|{ | |
|n=y; | |
|cout<< “N initialized\n”; | |
|} | |
|}; | |

20. What do you mean by static class members? Explain the characteristics of static class members with suitable examples. (8)
Ans: Static class member variables are used commonly by the entire class. It stores values. No different copies of a static variable are made for each object. It is shared by all the objects. It is just like the C static variables.
It has the following characteristics:
• On the creation of the first object of the class a static variable is always initialized by zero.
• All the objects share the single copy of a static variable.
• The scope is only within the class but its lifetime is through out the program.
An example is given below:
|#include<iostream.h> |int main() |
|using namespace std; |{ |
|class num |num o1,o2,o3; |
|{ |o1.getc(); |
|static int c; |o2.getc(); |
|int n; |o3.getc(); |
|public: |o1.getd(1); |
|void getd(int x) |o2.getd(2); |
|{ |o3.getd(3); |
|n =x; |cout<<"After reading data"<<"\n"; |
|c++; |o1.getc(); |
|} |o2.getc(); |
|void getc(void) |o3.getc(); |
|{ |return 0; |
|cout<<"count: "<<c<<"\n"; |} |
|} | |
|}; | |
|int num :: c; | |

21. Create a class Patient that stores the patient name (a string) and the disease (a string) of the patient. From this class derive two classes : In_patient which has a data member roomrent (type float) and Out_patient which has a data member OPD_charges (float). Each of these three classes should have a nondefault constructor and a putdata() function to display its data. Write a main() program to test In_ patient and Out_patient classes by creating instances of them and then displaying the data with putdata(). (10)
Ans:
|#include<iostream.h> |class out_patient:public patient |
|class patient |{ |
|{ |float opd_charges; |
|protected: |public: |
|char *name,*disease; |out_patient(char *n,char *d,float opd):patient(n,d) |
|public: |{ |
|patient(char *n,char *d) |opd_charges=opd; |
|{ |} |
|name=n; |void putdata() |
|disease=d; |{ |
|} |patient::putdata(); |
|void putdata() |cout<<"OPD charges is"<<opd_charges; |
|{ |} |
|cout<<"patient's name is"<<name<<endl; |}; |
|cout<<"Disease is"<<disease<<endl; |void main() |
|} |{ |
|}; |char *nm,*dis; |
|class in_patient:public patient |float rr1,op1; |
|{ |nm=new char; |
|float roomrent; |dis=new char; |
|public: |cout<<"Enter patient's name"<<endl; |
|in_patient(char *n,char *d,float rr):patient(n,d) |cin>>nm; |
|{ |cout<<"Enter disease"<<endl; |
|roomrent=rr; |cin>>dis; |
|} |cout<<"Enter room rent"<<endl; |
|void putdata() |cin>>rr1; |
|{ |cout<<"Enter opd charges"<<endl; |
|patient::putdata(); |cin>>op1; |
|cout<<"Room rent is"<<roomrent; |in_patient ip(nm,dis,rr1); |
|cout<<endl; |out_patient op(nm,dis,op1); |
|} |cout<<"Details of In_patient"<<endl; |
|}; |ip.putdata(); |
| |cout<<"Details of Out_patient"<<endl; |
| |op.putdata(); |
| |} |

22. Consider the following specifications: (8)
[pic]
(i) Declare structures in C++ for Name and Phone.
(ii) Declare a class N_rec with the following members.
1. Define the constructor (outside the class N_rec) that gathers the information from the user for Name and Phone.
2. Define the display_rec(outside the class N_rec) that shows the current values of the data members.
Ans:
|#include<iostream.h> |N_Rec :: N_Rec() |
|#include<conio.h> |{ |
|#include<string.h> |strcpy(name.First,"Shailesh"); |
|struct Name |strcpy(name.Mid," "); |
|{ |strcpy(name.Last,"Saurabh"); |
|char First[40], Mid[40], Last[60]; |strcpy(phone.Area,"011"); |
|}; |strcpy(phone.Exch,"64"); |
|struct Phone |strcpy(phone.Numb,"608284"); |
|{ |} |
|char Area[4], Exch[4], Numb[6]; |N_Rec :: Display_Rec() |
|}; |{ |
|class N_Rec |cout<<name.First<<" " <<name.Mid<<" "<<name.Last; |
|{ |cout<<endl<<phone.Area<<" "<<phone.Exch<<" "<<phone.Numb; |
|struct Name name; |}; |
|struct Phone phone; |main() |
|public: |{ |
|N_Rec(); |clrscr(); |
|Display_Rec(); |N_Rec obj1; |
|}; |obj1.Display_Rec(); |
| |getch(); |
| |} |

23. Write short notes on any TWO :-
(i) Procedure oriented vs object oriented programming.
(ii) Object oriented design.
(iii) User defined data types in C++. (2 x 7)
Ans:
(i) Procedure oriented vs object oriented programming
Procedure-oriented programming basically consists of writing a list of instructions (or actions) for the computer to follow, and organizing these instructions into groups known as functions . We normally use a flowchart to organize these actions and represent the flow of control from one action to another. While we concentrate on the development of functions, very little attention is given to the data that are being used by various functions. What happens to the data? How are they affected by the functions that work on them? In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we also need to revise all functions that access the data. This provides an opportunity for bugs to creep in. Another serious drawback with the procedural approach is that it does not model real world problems very well. This is because functions are action-oriented and do not really correspond to the elements of the problem.
Some characteristics exhibited by procedure-oriented programming are:
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as functions. Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.

Object-Oriented programming
The major motivating factor in the invention of object-oriented approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects.

Some of the striking features of object-oriented programming are:
• Emphasis is on data rather than procedure.
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are tied together in the data structure.
• Data is hidden and cannot be accessed by external functions. .
• Objects may communicate with each other through functions.
• New data and functions can be easily added whenever necessary.
• Follows bottom-up approach in program design.

Object-oriented programming is the most recent concept among programming paradigms and still means different things to different people. It is therefore important to have a working definition of object-oriented programming before we proceed further. We define "objectoriented programming as an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand." Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modifications.

ii) Object oriented design
Design is concerned with the mapping of objects in the problem space into objects in the solution space, and creating an overall structure (architectural model) and computational models of the system. This stage normally uses the bottom-up approach to build the structure of the system and the top-down functional decomposition approach to design :the class member functions that provide services. It is particularly important to construct structured hierarchies, to identify abstract classes, and to simplify the inter-object communications. Reusability of classes from the previous designs, classification of the objects into subsystems and determination of appropriate protocols are some of the 'considerations of the design stage. The object oriented design (OOD) approach may involve the following steps:
1. Review of objects created in the analysis phase.
2. Specification of class dependencies.
3. Organization of class hierarchies.
4. Design of classes.
5. Design of member functions.
6. Design of driver program.
Review of Problem Space Objects
The main objective of this review exercise is to refine the objects in terms of their attributes and operations and to identify other objects that are solution specific. Some guidelines that might help the review process are:
1. If only one object is necessary for a service (or operation), then it operates only on that object. 2. If two or more objects are required for an operation to occur, then it is necessary to identify which object's private part should be known to the operation.
3. If an operation requires knowledge of more than one type of objects, then the operation is not functionally cohesive and should be rejected.

Class Dependencies
It is important to identify appropriate classes to represent the objects in the solution space and establish their relationships. The major relationships that are important in the context of design are:
1. Inheritance relationship
2. Containment relationship.
3. Use relationships

Organization of Class Hierarchies
This involves identification of common attributes and functions among a group of related classes and then combining them to form new class. The new class serves as the super class and the other as a subordinate classes.

Design of Class
Given below are some guidelines which should be considered while designing a class:
1. The public interface of a class should have only functions of the class.
2. An object of one class should not send a message directly to a member of another class.
3. A function should be declared public only when it is required to be used by the objects of the class.
4. Each function either accesses or modifies some data of the class it represents.
5. A class should be dependent on as few (other) classes as possible.
6. Interactions between two classes must be explicit.
7. Each subordinate class should be designed as a specialization of the base class with the sole purpose of adding additional features.
8. The top class of a structure should represent the abstract model of the target concept.

Design of Member Functions
The member functions define the operations that are performed on the object's data.
These functions behave like any other C function and therefore we can use the top-down functional decomposition technique to design them.

Design of the Driver Program
The driver program is mainly responsible for:
1. Receiving data values from the user
2 Creating objects from the class definitions
3. Arranging communication between the objects as a sequence of messages for invoking the member functions, and
4. Displaying output results in the form required by the user.

(iii) User defined data types in C++
Structure and Classes
Data types such as struct and class is user defined data type in c++ example struct{ char title[50]; char author[50];
} book; class student{ char title[50]; char author[50]; public: void get()} student s1;

Enumerated data type
The enum keyword automatically enumerates a list of words by assigning them values 0,1,2 and so on

enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

24. When does ambiguity arise in multiple inheritance? How can one resolve it? Develop a program in C++ to create a derived class having following items: name, age, rollno, marks, empcode and designation. Design a base class student having data members as rollno, marks and the another base class is employee having data members as empcode and designation. These both base classes are inherited from a single base class person with data members name and age. The program should carry out the required input( ) and output( ) member functions for all. (12)
Ans:
A class can be derived such that it inherits the properties of two or more base classes. This is called multiple inheritance. Ambiguity occurs when the base classes have functions with same name. for example if two base classes have the function get_data().then which function will be used by the derived class? This problem can be solved be defining a named instance with the derived class, using the class resolution operator with the function name.
Program:
|#include<conio.h> |void disp_data() |
|#include<iostream.h> |{ |
|class person{ |cout<<"roll_no:"<<roll_no; |
|public: |cout<<'\n'; |
|char name[20]; |cout<<"marks:"<<marks; } |
|int age; |}; |
|void get_details(); |class employee:public person { |
|void disp_details(); |public: |
|}; |int emp_code; |
|void person::get_details() { |char desig[20]; |
|cout<<"enter name:"; |void get_details(int a,char *d) { |
|cin>>name; |emp_code = a; |
|cout<<"enter age:"; |strcpy(design, d); } |
|cin>>age; |void disp_data() { |
|} |cout<<"emp_code:"<<emp_code; |
|void person::disp_details() { |cout<<'\n'; |
|cout<<"name:"<<name; |cout<<"designation:"<<desig; } |
|cout<<'\n'; |}; |
|cout<<"age:"<<age; |void main(){ |
|cout<<'\n'; |int r,m,c;char d[20]; |
|} |cout<<"\n Enter roll_no. and marks :"; |
|class student: public person { |cin>>r,m |
|public: |cout<<"\n Enter employee code:"; |
|int roll_no; |cin>>c; |
|int marks; |cout<<"\n Enter designation: "; |
|void get_details(int a,int b) { |getline(d); |
|roll_no = a; |student ob1; |
|marks = b; |employee ob2; |
|} |ob1.get_details(r,m); |
| |ob2.get_details(c,d); |
| |ob1.disp_data(); |
| |ob2.disp_data();getch(); |
| |} |

25. Write two advantages of using include compiler directive. (4)
Ans: The include compiler directive is a preprocessor directive. Means, it is a command to the preprocessor. A preprocessor is a program that performs the preliminary processing with the purpose of expanding macro code templates to produce a C++ code. By including this header file, the function that we are using is replaced by the entire function definition. This is very helpful in case of small modules which are to be called several times in a program. It reduces the overhead cost of calling the function each time.

26. Explain the difference between macro & function. (5)
Ans:Difference between macro and function macroThe preprocessor will replace all the macro function used in the program by their function body before the compilation. The distinguishing feature of macro function are that there will be no explicit function call during execution, since the body is substituted at the point of macro call during compilation. Thereby the runtime overhead for the function linking or context-switch time is reduced. The directive # define indicates the start of a macro function as shown in the figure.
[pic]
Examples:
#define inc(a) a+1
#define add(a, b) (a+b)

Function:A function is a set of program statements that can be processed independer.tly. A function can be invoked which behaves as though its code is inserted at the point of the function call. The communication between a caller (calling function) and callee (called function) takes place through parameters. The functions can be designed, developed, and implemented independently by different programmers. The independent functions can be grouped to form a software library. Functions are independent because variable names and labels defined within its body are local to it. The use of functions offers flexibility in the design, development, and implementation of the program to solve complex problems. The advantages of functions includes the following:
• Modular programming
• Reduction in the amount of work and development time
• Program and function debugging is easier
• Division of work is simplitied due to the use of divide-and-conquer principle .
• Reduction in size of the program due to code reusability
• Functions can be accessed repeatedly without redevelopment, which in turn promotes reuse of code .
• Library of functions can be implemented by combining well designed, tested and proven function.
Function Components
Every function has the following elements associated with it:
1. Function declaration or prototype.
2. Function parameters (formal parameters)
3. Combination of function declaration and its definition.
4. Function definition (function declaration and a function body).
5. return statement.
6. Function call.
A function can be executed using a function call in the program. The various components associated with the function are shown in Figure
Void func(int a, int b); Function declaration
[pic]
27. What is Object Oriented Programming (OOP)? What are the advantages of Object Oriented Programming? (6)
Ans:
Ans: Object Oriented Programming (OOP) is an approach that provides a way of modulating programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.
The advantages of OOP are as follows:
• Function and data both are tied together in a single unit.
• Data is not accessible by external functions as it is hidden.
• Objects may communicate with each other only through functions.
• It is easy to add new data and functions whenever required.
• It can model real world problems very well.

28. What are the different storage classes in C++. (5)
Ans: STORAGE CLASSES
C++ provides 4 storage class specifiers:
AUTO, REGISTER, EXTERN, and STATIC
An identifier's storage class specifier helps determine its storage class, scope, and linkage.
Storage class - determines the period during which that identifier exists in memory
Scope - determines if the identifier can be referenced in a program
Linkage - determines for a mulitple-source-file program whether an identifier is known only in the current source file or in any source file with proper declarations.
Automatic storage class
The auto and register keywords are used to declare variables of the automatic storage class. Such variables are created when the block in which they are declared is entered, they exist while the block is active, and they are destroyed when the block is exited.
Example:
auto float x, y; declares that float variables x and y are local variables of automatic storage class, they exist only in the body of the function in which the definition appears. register int counter = 1; declares that the integer variable counter be placed in one of the computer's register and be initialized to 1. Either write auto or register but not both to an identifier.
Static Storage Class
The keywords extern and static are used to declare identifiers for variables and functions of the static storage class. Such variables exist from the point at which the program begins execution. There are two types of identifiers with static storage class: external identifiers (such as global variables and function names) and local variables declared with the storage class specifier static. Global variables and function names default to storage class specifier extern. Global variables are created by placing variable declarations outside any function definition. They retain their values throughout the execution of the program.

29. Write a program to overload the unary minus operator using friend function. (8)
Ans:
|#inlcude<iostream.h> |int main(){ |
|class space{ |space s; |
|int x; |s.getdata(10,-20,30); |
|int y; |cout<<"S : "; |
|int z; |s.display(); |
|public: |-s; |
|void getdata(int a,int b.int c); |cout<<"S :"; |
|void display(void); |s.display(); |
|friend void operator-(space &s); |return 0; |
|}; |} |
|void space :: getdata(int a,int b,int c){ | |
|x=a; | |
|y=b; | |
|z=c; | |
|} | |
|void space :: display(void){ | |
|cout<<x<<" "; | |
|cout<<y<<" "; | |
|cout<<z<<"\n"; | |
|} | |
|void operator-( space &s){ | |
|s.x=-s.x; | |
|s.y=-s.y; | |
|s.z=-s.z; | |
|} | |

30. Write a program in which a class has three data members: name, roll no, marks of 5 subjects and a member function Assign() to assign the streams on the basis of table given below:
Avg. Marks Stream
90% or more Computers
80% - 89% Electronics
75% - 79% Mechanical
70% - 74% Electrical
Ans:
|#include<iostream.h> |//cout<<sum; |
|class student |avg=sum/5; |
|{ |cout<<"Average marks is"<<avg; |
|char name[10]; |cout<<endl; |
|int rollno,marks[5],sum,avg; |if(avg>=90) |
|public: |{ |
|void assign() |cout<<"stream is Computer"<<endl; |
|{ |} |
|cout<<"enter name of the student"; |else |
|cin>>name; |{ |
|cout<<"enter rollno"; |if(avg>=80 && avg<=89) |
|cin>>rollno; |{ |
|cout<<"enter marks of five subjects"; |cout<<"stream is Electronics"; |
|for(int i=0;i<5;i++) |} |
|{ |if(avg>=75 && avg<=79) |
|cin>>marks[i]; |{ |
|} |cout<<"stream is Mechanical"; |
|sum=avg=0; |} |
|for(int j=0;j<5;j++) |if(avg>=70 && avg<=74) |
|{ |{ |
|sum=sum+marks[j]; |cout<<"stream is Electrical"; |
|} |} |
| |} |
| |} |
| |}; |
| |void main() |
| |{ |
| |student s1; |
| |s1.assign(); |
| |} |

31. Write a program to convert the polar co-ordinates into rectangular coordinates. (hint: polar co-ordinates(radius, angle) and rectangular co-ordinates(x,y) where x = r*cos(angle) and y = r*sin(angle)).
Ans:
|#include<iostream.h> |void main() |
|#include<math.h> |{ |
|using namespace std; |coord obj; |
|class coord |obj.polar(); |
|{ |obj.rectangular(); |
|float radius,angle,x,y; |obj.display(); |
|public: |} |
|polar(float r, float a); | |
|void rectangular(float x, float y); | |
|void display(); | |
|} | |
|void coord :: polar(float r,float a) | |
|{ | |
|cout<<"\n Enter the radius and angle : "; | |
|cin>>radius>>angle; | |
|} | |
|void coord :: rectangular(float x,float y) | |
|{ | |
|x=radius*cos(angle); | |
|y=radius*sin(angle); | |
|} | |
|void display() | |
|{ | |
|cout<<"\n The rectangular coordinates are : "<<x<<" and "<<y; | |
|} | |

What is multilevel inheritance? How is it different from multiple inheritance? (5)
Ans: Multilevel Inheritance
We can built hierarchies that contain as many layers of inheritance as we like. For example, given three classes called A, B and C, C can be derived from B, which can be derived from A. When this type of situation occurs, each derived class inherits all of the traits found in all of its base classes. In this case, C inherits all aspects of B and A. class A{…….}; //Base class class B: public A{…..}; // B derived from A class C:public B{……}; // C derived from B
This process can be extended to any numbers of levels
[pic]A
Multiple Inheritance.
When the number of base classes Inherited exceeds one then the type of inheritance is known as Multiple Inheritance.
For example in C++, The syntax:
Class D: public A, public B
{
//code
}
Indicates that D inherits the attributes of the two classes A and B. Though Multiple Inheritance sounds exciting and very useful it has its own drawbacks, owing to which most OOP languages deny support for this feature. These drawbacks include complexities involved when inheriting from many classes and the difficulty in managing such codes.

32. Write a C++ program to prepare the mark sheet of an university examination with the following items from the keyboard :
Name of the student
Roll no.
Subject name
Subject code
Internal marks
External marks
Design a base class consisting of data members Name of the student and Roll no. The derived class consists of the data members Subject name, Subject code, Internal marks and External marks. (9)
Ans:
|#include<iostream.h> |void get() |
|class student |{ |
|{ |student::get(); |
|char name[10]; |cout<<"enter subject name"; |
|int rollno; |cin>>subjectname; |
|public: |cout<<"enter subject code"; |
|void get() |cin>>subcode; |
|{ |cout<<"enter Internal marks"; |
|cout<<"enter student's name"<<endl; |cin>>intmarks; |
|cin>>name; |cout<<"enter External marks"; |
|cout<<"enter student's rollno"<<endl; |cin>>extmarks; |
|cin>>rollno; |} |
|} |void disp() |
|void disp() |{ |
|{ |student::disp(); |
|cout<<"Name of the student is : "<<name<<endl; |cout<<"Subject name is : "<<subjectname<<endl; |
|cout<<"Rollno is : "<<rollno<<endl; |cout<<"Subject code is : "<<subcode<<endl; |
|} |cout<<"Internal marks : "<<intmarks<<endl; |
|}; |cout<<"External marks : "<<extmarks<<endl; |
|class marks:public student |} |
|{ |}; |
|char subjectname[15]; |void main() |
|int subcode,intmarks,extmarks; |{ |
|public: |marks m; |
| |m.get(); |
| |m.disp(); |
| |} |

33. Explain the following:
(i) Non public constructors
(ii) Inline function
(iii) Virtual functions
(iv) Types of Inheritance. (4x4=16)
Ans:
i.) Non-public constructors: If a constructor is protected or private, it is called non-public constructor. We cannot create objects of a class that have non-public constructors. Only member function and friend function can create objects in this case. ii.) Inline functions: A function which is expanded in line is called an inline function.
Whenever we write there are certain costs associated with it such as jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function. To remove this overhead we write an inline function. It is a sort of request from the compiler. If we declare and define a function within the class definition then it is automatically inline.
Advantage of inline functions:
• They have no overhead associated with function cal or return mechanism
Disadvantage of inline functions:
• If the function made inline is too large and called regularly our program grows larger.
There are certain restrictions in which the compiler may apply like:- some compilers will not inline a function if it contains a static variable or if the function contains a loop, a switch , etc.. iii.) Virtual function: virtual functions are important because they support polymorphism at run time. A virtual function is a member function that is declared within the base class but redefined inside the derived class. To create a virtual function we precede the function declaration with the keyword virtual. Thus we can assume the model of “one interface multiple method”. The virtual function within the base class defines the form of interface to that function. It happens when a virtual function is called through a pointer.
The following is an example that illustrates the use of a virtual function:
|#include<iostream.h> |class derived1: public base |
|class base |{ |
|{ |public: |
|public: |derived1(int x): base(x){} |
|int i; |void func() |
|base(int x) |{ |
|{ |cout<<"\n using derived1 version"; |
|i=x; |cout<<i+i<<endl; |
|} |} |
|virtual void func() |}; |
|{ |int main() |
|cout<<"\n using base version of function"; |{ |
|cout<<i<<endl; |base *p; |
|} |base ob(10); |
|}; |derived d_ob(10); |
|class derived: public base |derived1 d_ob1(10); |
|{ |p=&ob; |
|public: |p->func(); |
|derived(int x):base(x){} |p=&d_ob; |
|void func() |p->func(); |
|{ |p=&d_ob1; |
|cout<<"\n sing derived version"; |p->func(); |
|cout<<i*i<<endl; |return 0; |
|} |} |
|}; | |

iv.) Inheritance: the mechanism of deriving a new class from an old one is called inheritance. The old class is called the base class and the new one is known as the derived class or sub class.
Types of inheritance
a. A derived class with only one base class is called single inheritance
b. A derived class with several base classes is called multiple inheritance.
c. When one base class is inherited by more than one class is called hierarchical inheritance. d. When one derived class inherits another derived class, it is called multilevel inheritance. [pic]
34. Write a program that shows the use of read() and write() to handle file I/O involving objects. (8)
Ans:
|#include<iostream.h> |int main() |
|#include<fstream.h> |{ |
|#include<iomanip.h> |INVENTORY item[3]; |
|class INVENTORY |fstream file; |
|{ |file.open("Stock.dat",ios::in|ios::out); |
|char name[10]; |cout<<"\n Enter details for three items \n"; |
|int code; |for(int i=0;i<3;i++) |
|float cost; |{ |
|public: |item[i].readdata(); |
|void readdata(void); |file.write((char *) & item[i],sizeof(item[i])); |
|void writedata(void); |} |
|}; |file.seekg(0); |
|void INVENTORY :: readdata(void) |cout<<"\nOutput\n"; |
|{ |for(i=0;i<3;i++) |
|cout<<"\n Enter name:";cin>>name; |{ |
|cout<<"\n Enter code:";cin>>code; |file.readdata((char *) &item[i],sizeof(item[i])); |
|cout<<"\n Enter cost:";cin>>cost; |item[i].writedata(); |
|} |} |
|void INVENTORY :: writedata(void) |file.close(); |
|{ |return 0; |
|cout<<setiosflags(ios::left) |} |
|<<setw(10)<<name | |
|<<setiosflags(ios::right) | |
|<<setw(10<<code) | |
|<<setprecision(2) | |
|<<setw(10)<<cost<<endl; | |
|} | |

35. Define a function area() to compute the area of objects of different classes – triangle, rectangle, square. Invoke these in the main program. Comment on the binding (static or dynamic) that takes place in your program. (10)
Ans:
|#include <iostream.h> // For input/output |cin >> length; |
|class triangle |cout << endl; // Go to a new line |
|{ |arear = breadth * length; |
|float base, height, areat; |cout << "\n\n\n\n\n\n\n\n\n"; // What is this line doing? |
|public: |cout << breadth << " is the length of the rectangle. \n\n"; |
|void area() |cout << length << " is the height of the rectangle. \n\n"; |
|{ |cout << arear << " is the area of the rectangle. \n\n"; |
|cout << "Enter the base of the triangle: "; |} |
|cin >> base; |}; |
|cout << endl; // Go to a new line | |
|cout << "Enter the height of the triangle: "; |class square |
|cin >> height; |{ |
|cout << endl; // Go to a new line |float side,areas; |
|areat = 0.5 * base * height; |public: |
|cout << "\n\n\n\n\n\n\n\n\n"; // What is this line doing? |void area() |
|cout << base << " is the base length of the triangle. \n\n"; |{ |
|cout << height << " is the height of the triangle. \n\n"; |cout << "Enter the height of the square: "; |
|cout << areat << " is the area of the triangle. \n\n"; |cin >> side; |
|} |cout << endl; // Go to a new line |
|}; |areas = side * side; |
|class rectangle |cout << "\n\n\n\n\n\n\n\n\n"; // What is this line doing? |
|{ |cout << side << " is the side of the square:. \n\n"; |
|float breadth, length, arear; |cout << areas << " is the area of the square:. \n\n"; |
|public: |} |
|void area() |}; |
|{ |main() |
|cout << "Enter the breadth of the rectangle: "; |{ |
|cin >> breadth; |triangle t; |
|cout << endl; // Go to a new line |rectangle r; |
|cout << "Enter the length of the rectangle: "; |square s; |
| |t.area(); |
| |r.area(); |
| |s.area(); |
| |return(0); |
| |} |

36. What are the basic differences between manipulators and ios member functions in implementation? Give examples. (8)
Ans:
The basic difference between manipulators and ios member functions in implementation is as follows:
The ios member function returns the previous format state which can be of use later on but the manipulator does not return the previous format state. Whenever we need to save the old format states, we must use the ios member functions rather then the manipulators. Example: an example program illustrating the formatting of the output values using both manipulators and ios functions is given below.
#include<iostream.h>
#include<iomanip.h> int main()
{
cout.setf(ios::showpoint); cout<<setw(5)<<"\n" <<setw(15)<<"Inverse_of_n"
<<setw(15)<<"Sum_of_terms\n\n";
double term,sum=0; for(int n=1;n<=10;n++)
{
term=1.0/float(n); sum+=term; cout<<setw(5)<<n
<<setw(14)<<setprecision(4)
<<setiosflags(ios::scientific)<<term
<<setw(13)<<resetiosflags(ios::scientific)
<<sum<<endl;
}
return 0;
}
37. Class Y has been derived from class X. The class Y does not contain any data members of its own. Does the class Y require constructor. If yes, why? (4)
Ans:Yes, it is mandatory for class Y to have a constructor. It is the responsibility of the derived class constructor to invoke the base class constructor by passing required arguments to it.Unless the constructor of class Y is invoked the data members of class X that have been inherited by class Y will not be given any values. Although class Y does not have any data member of its own, yet to use the data members inherited from X, Y needs a constructor. Y(type1 x, type2 y,…):

38. How can a common friend function to two different classes be declared? (4)
Ans:
Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the classs scope, and they are not called using the member-selection operators (. and >) unless they are members of another class. Any data which is declared private inside a class is not accessible from outside the class. A function which is not a member or an external class can never access such private data. But there may be some cases, where a programmer will need need access to the private data from non-member functions and external classes. C++ offers some exceptions in such cases. A class can allow non-member functions and other classes to access its own private data, by making them as friends. This part of C++ tutorial essentially gives two important points. Once a non-member function is declared as a friend, it can access the private data of the class similarly when a class is declared as a friend, the friend class can have access to the private data of the class which made this a friend.
39. Explain any three drawbacks of procedure oriented languages. Give an example each in C language to highlight the drawback. (6)
Ans: Drawbacks of procedure oriented languages.
Previously, programs were written in a procedural fashion i.e. the statements were written in the form of a batch. But as the requirements grew, it was seen that the programs were getting larger and larger and it became difficult to debug. So functions were introduced to reduce the size of the programs and improve readability in them. Still that was not enough. One of the major problems with the “Procedural Paradigm” was that data was treated as a stepson and functions were given more priority. Where as, it is the other way. In this procedure the original data could easily get corrupted, as it was accessible to all the functions, even to those which do not have any right to access them. Before OOP, the programmer was restricted to use the predefined data types such as integer, float and character. If any program required handling of the x-y coordinates of some point then it is quite a headache for the programmer. Where as, in OOP this can be handled very easily as the programmer can define his own data types and the corresponding functions.

40. Explain the difference between constructor and copy constructor in C++. Which of these is invoked in the following statement
Date D1 (D2); where D2 is also an object of class Date. (3)
Ans: Constructors are special `member functions' of which exactly one is called automatically at creation time of an object. Which one depends on the form of the variable declaration. Symmetrically, there exists a destructor, which is automatically called at destruction time of an object.
Three types of constructors are distinguished: default constructor, copy constructor, and all others (user defined). A constructor has the same name as the class and it has no return type. The parameter list for the default and the copy constructor are fixed. The user-defined constructors can have arbitrary parameter lists following C++ overloading rules.
|class A { |int main() { |
|int i; // private |A a1; // calls the default constructor |
|public: |A a2 = a1; // calls the copy constructor (not the assignment |
|A(); // default constructor |operator) |
|A( const A& a); // copy constructor |A a3(a1); // calls the copy constructor (usual constructor call |
|A( int n); // user defined |syntax) |
|~A(); // destructor |A a4(1); // calls the user defined constructor |
|}; |} // automatic destructor calls for a4, a3, a2, a1 at the end of |
| |the block |
| | |

The compiler generates a missing default constructor, copy constructor, or destructor automatically. The default implementation of the default constructor calls the default constructors of all class member variables. The default constructor is not automatically generated if other constructors are explicitly declared in the class (except an explicit declared copy constructor).
The default copy constructor calls the copy constructor of all class member variables, which performs a bitwise copy for built-in data types. The default destructor does nothing. All default implementations can be explicitly inhibited by declaring the respective constructor/destructor in the private part of the class.
Constructors initialize member variables. A new syntax, which resembles constructor calls, allows to call the respective constructors of the member variables (instead of assigning new values). The constructor call syntax extends also to built-in types. The order of the initializations should follow the order of the declarations, multiple initializations are separated by comma. class A { int i; // private public: A() : i(0) {} // default constructor
A( const A& a) : i(a.i) {} // copy constructor, equal to the compiler default
A( int n) : i(n) {} // user defined
~A() {} // destructor, equal to the compiler default
};

Usually, only the default constructor (if the semantics are reasonable), and some user defined constructors are defined for a class. As soon as the class manages some external resources, e.g., dynamically allocated memory, the following four implementations have to work together to avoid resource allocation errors: default constructor, copy constructor, assignment operator, and destructor. Note that the compiler would create a default implementation for the assignment operator if it is not defined explicitly

41. Define a class Rectangle which has a length and a breadth. Define the constructors and the destructor and member functions to get the length and the breadth. Write a global function which creates an instance of the class Rectangle and computes the area using the member functions. (8)
Ans:
|#include <iostream.h> |int area(CRectangle r) |
|class CRectangle { |{ |
|int width, height; |return r.height * r.width; |
|public: |} |
|CRectangle (int,int); |int main () { |
|~CRectangle (); |int h,w; |
|friend int area(CRectangle); |cout<<"enter length and breadth of rectangle"; |
|}; |cin>>h>>w; |
|CRectangle::CRectangle (int a, int b) { |CRectangle rect (h,w); |
|width = a; |cout << "area: " <<area(rect)<< endl; |
|height = b; |return 0; |
|} |} |
|CRectangle::~CRectangle () { | |
|// delete width; | |
|//delete height; | |
|} | |

42. Why is destructor function required in class? What are the special characteristics of destructors? Can a destructor accept arguments? (8)
Ans: Destructor: A destructor is used to destroy the objects that have been created by a constructor. It has the same name as that of the class but is preceded by a tilde. For example,
~integer () {}
Characteristics:
• A destructor is invoked implicitly by the compiler when we exit from the program or block.It releases memory space for future use.
• A destructor never accepts any argument nor does it return any value.
• It is not possible to take the address of a destructor.
• Destructors can not be inherited.
• They cannot be overloaded
For example, the destructor for the matrix class will defined as follows: matrix :: ~matrix()
{
for(int i=0;i<d1;i++) delete p[i]; delete p;
}
43. Define a class Deposit which has a principal, a rate of interest which is fixed for all deposits and a period in terms of years. Write member functions to
(i) alter(float) which can change the rate of interest.
(ii) interest() which computes the interest and returns it.
(iii) print() which prints data as shown below. Note that the width of each column is 20. (10)
Principal Year Interest
1100.00 1 100.00
Ans:
|#include<iostream.h> |void print() |
|class deposit |{ |
|float p,r,t,i; |cout << "Principal = Rs" << p << endl; |
|public: |cout << "Rate = " << r << "%" << endl; |
|float interest() |cout << "Time = " << t << " years" << endl; |
|{ |cout << "Simple Interest = Rs" << i << endl; |
|cout << "Enter the principal, rate & time : " << endl; |} |
|cin>>p>>r>>t; |}; |
|i=(p*r*t)/100; |void main() |
|return i; |{ |
|} |deposit d; |
| |d.interest(); |
| |d.print(); |
| |} |

44. Differentiate and give examples to bring out the difference between
(i) private and public inheritance. (iii) static and dynamic binding.
(iv) a class and a struct. Ans:
i) private and public inheritance
In private inheritence the public members of the base class become private members of thederived class. Therefore the object of derived class cannot have access to the public member function of base class. In public inheritance the derived class inherit all the public members of the base class and retains their visibility. Thus the public member of the base class is also the public member of the derived class.
Class a
{
int x; public: void disp()
{
}
};
class y : private a
{
int c; public: void disp()
{
}
};
so when d.disp() // disp() is private; iii) Static and Dynamic binding
The information is known to the compiler at the compile time and, therefore compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding. The linking of function with a class much later after the compilation, this process is termed as late binding or dynamic binding because the selection of the appropriate function is done dynamically at run time. This requires the use of pointers to objects. iv)a class and a struct
A class is a logical method to organize data and functions in the same structure. They are declared using keyword class, whose functionality is similar to that of the C keyword struct, but with the possibility of including functions as members, instead of only data.
Its form is: class class_name { permission_label_1: member1; permission_label_2: member2;
... } object_name; where class_name is a name for the class (user defined type) and the optional field object_name is one, or several, valid object identifiers. The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords: private:, public: or protected:
In struct all members declared are public by default.
Struct student{ char name[10]; int age;}stud;
Both struct and class is used as user defined data type.

45. Explain the order in which constructors are invoked when there is multiple inheritance. (4)
Ans: The order in which constructor is invoked when there is multiple inheritance is order in which the class is derived that is constructor of base class will invoke first and then the constructor of derived class and so on. The destructor will invoke in reverse order than constructor. That is destructor of derived class will invoke first and then base class. Example
|Class a |void main() |
|{ |{ |
|a() |b b1; |
|{ |} |
|cout<<”constructor a”; |output |
|} |constructor a |
|~a() |constructor b |
|{ |destructor b |
|cout<<”destructor a”; |destructor a |
|} | |
|}; | |
|class b : public a | |
|{ | |
|b() | |
|{ | |
|cout<<”constructor b”; | |
|} | |
|~b() | |
|{ | |
|cout<<”destructor b”; | |
|} | |
|}; | |

46. Define a class Publication which has a title. Derive two classes from it – a class Book which has an accession number and a class Magazine which has volume number. With these two as bases, derive the class Journal. Define a function print() in each of these classes. Ensure that the derived class function always invokes the base(s) class function. In main() create a Journal called IEEEOOP with an accession number 681.3 and a volume number 1. Invoke the print() function for this object. (10)
Ans:
|#include<iostream.h> |class magazine:public publication |
|class publication |{ |
|{ |int volumeno; |
|char title[40]; |public: |
|float price; |void getdata() |
|public: |{ |
|void getdata() |publication::getdata(); |
|{ |cout<<"Enter Volume number of magazine"; |
|cout<<"Enter publication:"; |cin>>volumeno; |
|cin>>title; |} |
|cout<<"Enter price"; |void print() |
|cin>>price; |{ |
|} |publication::print(); |
|void print() |cout<<"Volume number is"<<volumeno<<endl; |
|{ |} |
|cout<<"\tPublication ="<<title<<endl; |}; |
|cout<<"\tPrice="<<price<<endl; |class journal:public book,public magazine |
|} |{ |
|}; |char name[20]; |
|class book:public publication |public: |
|{ |void getdata() |
|int accessionno; |{ |
|public: |book::getdata(); |
|void getdata() |magazine::getdata(); |
|{ |cout<<"enter name of journal"; |
|publication::getdata(); |cin>>name; |
|cout<<"Enter Accession number"; |} |
|cin>>accessionno; |void print() |
|} |{ |
|void print() |cout<<"name of journal is"<<name<<endl; |
|{ |book::print(); |
|publication::print(); |magazine::print(); |
|cout<<"Accession number is"<<accessionno; |} |
|} |}; |
|}; |void main() |
| |{ |
| |journal j; |
| |j.getdata(); |
| |j.print(); |
| |} |

47. Define a class Date. Overload the operators += and <<. (10)
Ans:
|Date class |friend ostream & operator << (ostream &out,time &t) |
|#include<iostream.h> |{ |
|#include<conio.h> |out<<t.hr<<":"; |
|class time |out<<t.min<<":"; |
|{ |void main() |
|private: int hr,min,sec; |{ |
|public: |clrscr(); |
|void getdata(); |time t1,t2; |
|void operator +=(time a1); |t1.getdata(); |
|out<<t.sec; |t2.getdata(); |
|return out; |t1+=t2; |
|} |cout<<"\n RESULT OF ADDITION"<<endl; |
|}; |cout<<t1; |
|void time::getdata() |getch(); |
|{ |} |
|cout<<"ENTER THE HOURS"<<endl; | |
|cin>>hr; | |
|cout<<"ENTER THE MINUTES"<<endl; | |
|cin>>min; | |
|cout<<"ENTER THE SECONDS"<<endl; | |
|cin>>sec; | |
|} | |
|void time::operator +=(time a1) | |
|{ | |
|hr=hr+a1.min; | |
|min=min+a1.min; | |
|sec=sec+a1.sec; | |
|if(sec>=60) | |
|{ | |
|min++; | |
|sec=sec-60; | |
|} | |
|if(min>=60) | |
|{ | |
|hr++; | |
|min-=60; | |
|} | |
|} | |

48. What are abstract classes? How do you define one and how is it useful in a typical library? (4)
Ans: A class that contains at least one pure virtual function is considered an abstract class. classes derived from the abstract class must implement the pure virtual function or they, too, are abstract classes.

class Account
{
public:
Account( double d ); // Constructor. virtual double GetBalance(); // Obtain balance. virtual void PrintBalance() = 0; // Pure virtual function. private: double _balance;
};

Abstract classes act as expressions of general concepts from which more specific classes can be derived. You cannot create an object of an abstract class type; however, you can use pointers and references to abstract class types.

49. Define a class City which has name and pincode. Define another class Address which has house no and city of type City. Define the constructor, the destructor and a function print() which prints the address. Create an object of type Address in main() and print it. (10)
Ans:
|#include<iostream.h> |void print() |
|class city |{ |
|{ |cout<<"city name is"<<cty.name; |
|public: |cout<<"pincode is"<<houseno.pin; |
|char *name; |} |
|int pin; |}; |
|public: |void main() |
|city() |{ |
|{ |address ad("Kathma",23),ad1("Rohini",85); |
|} |ad.print(); |
|city(char nm[],int pn) |ad1.print(); |
|{ |} |
|name=nm; | |
|pin=pn; | |
|} | |
|}; | |
|class address | |
|{ | |
|public: | |
|city houseno,cty; | |
|address(char ct[],int hn) | |
|{ | |
|cty.name=ct; | |
|houseno.pin=hn; | |
|} | |

Describe the different modes in which files can be opened in C++. (4)
Ans: Different modes in which files can be opened in C++.
[pic]
50. Define a class Car which has model and cost as data members. Write functions
(i) to read the model and cost of a car from the keyboard and store it a file CARS.
(ii) to read from the file CARS and display it on the screen. (10)
Ans:
|#include<iostream.h> |void read_file() |
|#include<fstream.h> |{ |
|class car |ifstream ifs("car.dat"); |
|{ |while(ifs) |
|char model[10]; |{ ifs>>model>>cost; |
|float cost; |} |
|public: |ifs.close(); |
|void read() |cout<<"Model"<<model<<endl; |
|{ |cout<<"Cost"<<cost; |
|cout<<"\n Enter model of car"; |}}; |
|cin>>model; |void main() |
|cout<<"\n Enter cost of car"; |{ car c; |
|cin>>cost; |c.read(); |
|ofstream of("car.dat",ios::app); |c.read_file();} |
|of<<model; | |
|of<<cost; | |
|of.close(); } | |

51. What is the output of the following program segment? float pi = 3.14167234; int i=1, j=2; cout.fill(‘$’); cout.ios::precision(5); cout.ios::width(10); cout<<i*j*pi<<‘\n’; (2)
Ans: The output is $$$$6.2833.
52. Given class Confusion { };
What is the difference between Confusion C; and Confusion C( ); (2)
Ans:
The difference between Confusion C; and Confusion C() is that Confusion C() invoke constructor with an argument whereas Confusion C invoke default constructor;

53. What are the shortcomings of procedure oriented approach? (8)
Ans: Programming, using languages such as COBOL, FORTRAN and C is known as procedure oriented programming (POP).The problem with POP is that in this approach things are done in a sequential manner. A number of functions are written for this. The drawbacks of POP are as follows:
i. In POP groups of instructions are written which are executed by the compiler in a serial manner. ii. POP contains many functions, and important data items are made global so that they are easily accessible by all the functions. Global data are more prone to undesirable changes which can be accidently made by a function iii. Another drawback is that it “does not model real world problems” very well. iv. In POP, data moves openly around the system from one function to another.
Functions can transform data into different forms.

54. What is encapsulation? What are its advantages? How can encapsulation be enforced in C++? (6)
Ans: Encapsulation: The wrapping up of data and functions into a single unit is called encapsulation. The data can only be accessed by the function with which they have been tied up and not by the outside world. It creates an interface between the object’s data and the program. A common use of information hiding is to hide the physical storage layout for data so that if it is changed, the change is restricted to a small subset of the total program. For example, if a three-dimensional point (x, y, z) is represented in a program with three floating point scalar variables and later, the representation is changed to a single array variable of size three, a module designed with information hiding in mind would protect the remainder of the program from such a change. In object-oriented programming, information hiding reduces software development risk by shifting the code's dependency on an uncertain implementation (design decision) onto a welldefined interface. Through encapsulation, we can provide security to our data function. Encapsulation can be enforced in C++ using the concept of classes which binds data and function together. Private data and member functions will not be visible to outside world. For example, in the following class two members x, y declared as private can be accessed only by the member functions, not even in main( ) we can call these data members.
|class XY |void XY::dispdata() |
|{ |{ cout<<a<<b; |
|int x,y; |} |
|public: |void main() |
|void getdata(); |{ XY xy1,xy2; |
|void dispdata(); |xy1.getdata(); |
|}; |xy2.dispdata(); |
|void XY::getdata() |} |
|{ cout<< “Enter two values\n”; | |
|cin>>a>>b; | |
|} | |

55. How are member functions different from other global functions? (2)
Ans: A member function and a non –member function are entirely different from each other. A member function has full access to the private data members of a class. A member function can directly access the data members without taking the help of an object. For calling member function in main(), dot operator is required along with an object. A member function cannot be called without an object outside the class.
A non member function cannot access the private members of a class. Non-member function are called in main( ) without using an object of a class.

56. Define a class Word which can hold a word where the length of the word is specified in the constructor. Implement the constructor and the destructor. (6)
Ans:
|#include<iostream.h> |void main() |
|#include<conio.h> |{ |
|#include<stdio.h> |char *w1="Girl"; |
|#include<string.h> |Word word1(w1); |
|class Word |Word word2("Good"); |
|{ |word1.display(); |
|char *word; |word2.display(); |
|int length; |} |
|public: | |
|Word() | |
|{ | |
|length=0; | |
|word=new char[length+1]; | |
|} | |
|Word(char *s) | |
|{ | |
|length=strlen(s); | |
|word=new char[length+1]; | |
|strcpy(word,s); | |
|} | |
|void display() | |
|{ cout<<word<<"\n"; | |
|} | |
|}; | |

57. Differentiate and give examples to bring out the difference between
(i) function overloading and function overriding
(ii) function template and inline functions
(iii) default constructor and copy constructor
(iv) public and private access specifiers (3.5 x 4 = 14)
Ans:
(i). Function overloading and function overriding:
Function overloading means the use of the same function name to create functions that perform a variety of different tasks. The functions would perform different operations depending on the argument list in the function call. The correct function to be invoked is selected by seeing the number and type of the arguments but not the function type. For example an overloaded function volume() handles different types of data as shown below: int volume(int s); double volume(double r, int h); long volume(long l, long b,int h);
Function overridding is used to describe virtual function redefinition by a derived class. This is useful when we want to have multiple derived classes implementing a base class function. We can put the common code to all of the derived classes in the base class function, and then in each of the derived class functions we can add the code specific to each one, and then just invoke the parent method. It differs from function overloading in the sense that all aspects of the parameters should be same when a overridden function is redefined in derived class.
Inline Function:
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. Instead of transferring control to and from the function code segment, a copy of the function body may be substituted directly for the function call. In this way, the performance overhead of a function call is avoided. A function is declared inline by using the inline function specifier or by defining a member function within a class or structure definition. The inline specifier is only a suggestion to the compiler that an inline expansion can be performed; the compiler is free to ignore the suggestion.
The following code fragment shows an inline function definition.

inline int add(int i, int j) { return i + j;}

(iii) Default constructor and copy constructor
Dafault constructor: A constructor that accepts no argument is called default constructor. This default constructor takes no parameters, or has default values for all parameters. The default constructor for the class A is A::A(). If no such constructor is defined, then the compiler supplies a default constructor. A default parameter is one where the parameter value is supplied in the definition. For example in the class A defined below 5 is the default value parameter.

Class A
{ int value;
Public:
A(int param=5)
{
value = param;
}
};

A copy constructor is a special constructor in the C++ programming language used to create a new object as a copy of an existing object. This constructor takes a single argument: a reference to the object to be copied. Normally the compiler automatically creates a copy constructor for each class (known as an implicit copy constructor) but for special cases the programmer creates the copy constructor, known as an explicit copy constructor. In such cases, the compiler doesn't create one. For example the following will be valid copy constructors for class A.

A(A const&);
A(A&);
A(A const volatile&);
A(A volatile&);

(iv)Public and Private access specifiers:
The keywords public and private are visibility labels. When the data members of a class are declared as private, then they will be visible only within the class. If we declare the class members as public then it can be accessed from the outside world also. Private specifier is used in data hiding which is the key feature of object oriented programming. The use of the keyword private is optional. When no specifier is used the data member is private by default. If all the data members of a class are declared as private then such a class is completely hidden from the outside world and does not serve any purpose. class class-name
{
private: int x,y;//No entry to private area private: int a,b;//entry allowed to public area
}

58. The keyword ‘virtual’ can be used for functions as well as classes in C++. Explain the two different uses. Give an example each. (6)
Ans: Virtual function: virtual functions are important because they support polymorphism at run time. A virtual function is a member function that is declared within the base class but redefined inside the derived class. To create a virtual function we precede the function declaration with the keyword virtual. Thus we can assume the model of “one interface multiple method”. The virtual function within the base class defines the form of interface to that function. It happens when a virtual function is called through a pointer.The following example illustrates the use of a virtual function:
|#include<iostream.h> |class derived1: public base |
|class base |{ |
|{ |public: |
|public: |derived1(int x): base(x){} |
|int i; |void func() |
|base(int x) |{ |
|{ |cout<<"\n using derived1 version"; |
|i=x; |cout<<i+i<<endl; |
|} |} |
|virtual void func() |}; |
|{ |int main() |
|cout<<"\n using base version of function"; |{ |
|cout<<i<<endl; |base *p; |
|} |base ob(10); |
|}; |derived d_ob(10); |
|class derived: public base |derived1 d_ob1(10); |
|{ |p=&ob; |
|public: |p->func(); |
|derived(int x):base(x){} |p=&d_ob; |
|void func() |p->func(); |
|{ |p=&d_ob1; |
|cout<<"\n using derived version"; |p->func(); |
|cout<<i*i<<endl; |return 0; |
|} |} |
|}; | |

Virtual class: The concept of virtual class is very important as far as inheritance is concerned. Basically, the need for a making a class virtual arises when all the three basic types of inheritance exist in the same program- Multiple, multilevel and hierarchical inheritance. For instance suppose we create a class child which inherit the properties of two other classes parent1 and parent2 and these two parent classes are inherited from a grandparent class. The grandfather class is the indirect base class for child class. Now the class child will have properties of the grandfather class but inherited twice, once through both the parents. The child can also inherit the properties straight from its indirect base class grandfather. To avoid the ambiguity caused due to the duplicate sets of inherited data we declare the common base class as virtual. Those classes that directly inherit the virtual class will be declared as follows:

class grandparents
{
....
....
}; class parent1: virtual public grandparents
{
....
....
}; class parent2: public virtual grandparents
{
....
....
}; class child: public parent1,public parent2
{
....//only one copy of grandparents
....//will be inherited.
};

59. Define a class Bag(duplicate values permitted) of 50 integers. The values of the integers is between 1 and 10. Overload the subscript operator[]. (6)
Ans:
|#include <iostream.h> |Bag::Bag(int *x) |
|class Bag |{ int size=sizeof(x); |
|{ |for(int i=0;i<size;i++) |
|int val[50]; |val[i]=x[i]; |
|int size; |} |
|public: |void main() |
|Bag(); |{ Bag b1; |
|Bag(int *x); |int x[50],n; |
|int &operator[](int i) |cout<<"How many values u want to put in bag"; |
|{ return val[i]; |cin>>n; |
|} |cout<<"Enter values between 1 to 10"; |
|}; |for(int i=0;i<n;i++) |
|Bag::Bag() |cin>>x[i]; |
|{ size=50; |b1=x; |
|for(int i=0;i<50;i++) |cout<<"values in the bags\n"; |
|val[i]=0; |for(i=0;i<n;i++) |
|} |cout<<x[i]<<"\n"; |
| |} |

60. What is the output of the following program segment? void main(){ char buffer[80]; cout<< “Enter a line with *: ”<<endl; cin.get(buffer, 8, ‘*’); cout << “The buffer contains ” << buffer << endl;}
Input : Hello World*
Ans: output:- The buffer contains HELLO W

61. What does the poem.txt contain? void main()
{
ofstream outfile(“poem.txt”); outfile << “Mary had a lamb”; outfile.seekp(11, ios::beg); outfile << “little”;
}
Ans: poem.txt contain : Mary had a little lamb

62. Given int * entry = new int [10];
Write code to fill the array with 10 numbers entered through the keyboard.
Ans:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr(); int *entry=new int[10]; cout<<"\n Enter ten numbers; "; for(int i=0;i<10;i++) cin>> entry[i]; for(i=0;i<10;i++) cout<<entry[i]<<”\n”; getch(); }
63. What is the output of the following program segment? void main() { int i = 6; double d = 3.0; char * str = “OOP”; cout.setf(ios::left);cout.setf(ios::fixed); cout << setfill(‘#’) << setw(5) << str; cout << setprecision(1) << i + d;
}
Ans: output:- OOP##9

64. What is the output of the following program segment? void main ( )
{ int xyz = 333; cout << endl <<
“The output is \n” << endl
; cout << “x\ y\ z\
= ”
<< xyz;
}
Ans: output:- the output is xyz=333 65. Assume that the cell users are two kinds – those with a post paid option and those with a prepaid option. Post paid gives a fixed free talk time and the rest is computed at the rate of Rs.1.90 per pulse. Prepaid cards have a fixed talk time.
Define a class Cell_user as a base class and derive the hierarchy of classes. Define member functions and override them wherever necessary to
(i) retrieve the talk time left for each user.
(ii) print the bill in a proper format containing all the information for the post paid user. (14)
Ans:
|class Cell_User |void post::showdata() |
|{ protected: |{ |
|char cellno[15]; |cout<<"\nPostpaid User\n"; |
|char name[25], add[50]; |cout<<"\nFreepulse="<<freepulse; |
|public: |cout<<"\nUsedpulse="<<usedpulse; |
|char plan; |extra=usedpulse-freepulse; |
|void getdata(); |cout<<"\n Extra pulses:"<<'\t'<<extra; |
|void showdata(); |if (extra>0) |
|}; |{ |
|void Cell_User::getdata() |cout<<"\nMonthly Rent="<<600; |
|{ |cout<<"\nCall charges="<<extra*1.90; |
|cout<<endl<<"Enter your Name:-> "; |cout<<"\nTotal="<<600+extra*1.90; |
|cin.getline(name,25); |} |
|cout<<endl<<"Enter your Address:-> "; |else |
|cin.getline(add,50); |{ cout<<"\nMonthly Rent="<<600; |
|cout<<endl<<"Enter Cell Number:-> "; |cout<<"\nNo extra charges\n"; |
|cin>>cellno; |} |
|cout<<endl<<"Enter Plan ('O' for Post Paid and 'R' for Pre |} |
|Paid:-> "; |class pre : public Cell_User |
|cin>>plan; |{ |
|} |int talktime, usedtime,lefttime; |
|void Cell_User::showdata() |public: |
|{ cout<<"\nName:"<<'\t'<<name; |pre() |
|cout<<"\nCellno:"<<'\t'<<cellno; |{ |
|cout<<"\nAddress:"<<'\t'<<add<<"\n\n"; |talktime=50; |
|cout<<"Plan:"<<'\t'<<plan; |usedtime=0; |
|} |} |
|class post : public Cell_User |void getdata() |
|{ |{ |
|int freepulse, usedpulse,extra; |cout<<"\nEnter used Time for this user in Pulses:-> "; |
|public: |cin>>usedtime; |
|post() |} |
|{ |void showdata() |
|freepulse=50; |{ |
|usedpulse=0; |cout<<"\nFree talk time="<<talktime; |
|} |cout<<"\nUsed talk time"<<usedtime; |
|void getdata() |lefttime=talktime-usedtime; |
|{cout<<"\nEnter used Time for this user in Pulses:-> "; |if(lefttime>0) |
|cin>>usedpulse; |cout<<"\n Time left:"<<'\t'<<lefttime; |
|} |else |
|void showdata(); |cout<<"\n Please recharge your coupan\n"; |
|}; |} |
| |}; |
| |void main() |
| |{ clrscr(); |
| |Cell_User c; |
| |c.getdata(); |
| |if(c.plan=='O') |
| |{ |
| |post obj1; |
| |obj1.getdata(); |
| |c.showdata(); |
| |obj1.showdata(); |
| |} |
| |if(c.plan=='R') |
| |{ pre obj2; |
| |obj2.getdata(); |
| |c.showdata(); |
| |obj2.showdata(); |
| |} |
| |getch(); |
| |} |

66. Explain the I/O stream hierarchy in C++. (4)
Ans:
[pic]
The above hierarchies of classes are used to define various streams which deal with both the console and disc files. These classes are declared in the header file iostream. ios is the base for istream, ostream and iostream base classes. ios is declared as a virtual base class so that only one copy of its members are inherited by the iostream. The three classes istream_withassign, ostream_withassign iostream_withassign ostream_withassign and iostream_withassign are used to add assignment operators to these classes.
67. Define a class License that has a driving license number, name and address. Define constructors that take on parameter that is just the number and another where all parameters are present. (6)
Ans:
|#include<iostream.h> |void showdata() |
|#include<conio.h> |{ |
|#include<stdio.h> |cout<<endl<<dlno<<'\t'<<name<<'\t'<<add; |
|#include<string.h> |} |
|#include<fstream.h> |}; |
|#include<stdlib.h> |Q.106 Create a file and store the License information. (4) |
|class License |Ans: |
|{ |void main() |
|long dlno; |{ |
|char name[25],add[50]; |class License obj1(101),obj2(102,"Ramesh","Laxminagar"); |
|public: |fstream file; |
|License() |file.open("List.TXT",ios::in | ios::out); |
|{ |if (file==NULL) |
|dlno=0; |{ |
|strcpy(name, " "); |cout<<endl<<"Memory Allocation Problem."; |
|strcpy(add, " "); |getch(); |
|} |exit(1); |
|License(long no) |} |
|{ |class License obj; |
|dlno=no; |obj.getdata(); |
|strcpy(name," "); |file.write((char *) & obj, sizeof(obj)); |
|strcpy(add, " "); |file.seekg(0); |
|} |cout<<endl<<"Following informations are stored in the file:\n"; |
|License(long no, char n[25], char ad[50]) |while(1) |
|{ |{ |
|dlno=no; |file.read((char *) &obj, sizeof(obj)); |
|strcpy(name,n); |if (file) |
|strcpy(add,ad); |obj.showdata(); |
|} |else |
|void getdata() |break; |
|{ |} |
|cout<<endl<<"Enter your name:-> "; |} |
|cin>>name; | |
|cin.get(); | |
|cout<<endl<<"Enter your address:-> "; | |
|cin.getline(add,50); | |
|cout<<endl<<"Enter License Number:-> "; | |
|cin>>dlno; | |
|} | |

68. Write short notes on
(i) Constructor
(ii) Stream
(iii) Access control.
(iv) Friend. (3.5 x4 )
Ans:
i) Constructor:
A constructor is a member function which has the same name as at that of the class. It is used to initialize the data members of the class. A constructor is automatically invoked by the compiler when an object is created. A constructor which does not take any arguments is called default constructor.
The restrictions applied to a constructor are:
• A constructor cannot have any return type as it does not return any value.
• A constructor should be declared in the public part of the class.
• A derived class can call the constructor of the base class but a constructor is never inherited. • A constructor function cannot be made virtual.
• That object which has a constructor cannot be used as a member of the union.

C++ provides us with very helpful feature i.e., copy constructor. It is the mechanism in which we can declare and initialize an object from another both belonging to the same class. For example, the following statement will create an object obj2 and also initialize it by taking values from obj1. integer obj2(obj1);

We can also use the following instead the above for the same purpose. integer obj2=obj1; This process of initializing objects using copy constructor is known as “copy initialization”. Another statement obj2=obj1 will not assign the values using the copy constructor. Although the statement is valid this can be done using operator overloading. A copy constructor accepts a reference to an object of the same class as an argument. We cannot pass an argument by value to a copy constructor.
The following is an example program:
|#include<iostream.h> |int main() |
|class item |{ |
|{ |item obj(12); |
|int code; |item obj2(obj1); |
|public: |item obj3=obj1; |
|item(){} |item obj4; |
|item(int n){code=n;} |obj4=obj1;//copy constructor not called |
|item(item & a) |cout<<"\n code of obj1 : "; |
|{ |obj1.show(); |
|code=a.code; |cout<<"\n code of obj2 : "; |
|} |obj2.show(); |
|void show(void) |cout<<"\n code of obj3 : "; |
|{cout<<code;} |obj3.show(); |
|}; |cout<<"\n code of obj4 : "; |
| |obj4.show(); |
| |} |

ii) Stream: Stream is defined as an interface supplied by the I/O system to the programmer and that which is independent of the actual device being used. Stream is actually a sequence of bytes. These are basically of two types: one is when it is a source through which input can be taken and the other is when it acts as a destination to which output can be sent. The source stream is called the input stream and the destination stream is called the output stream. There are several streams likewise cin is an input stream which extracts input from the keyboard and cout is the output stream which inserts the ouput to the screen. The three streams used are:-

• istream(input stream).this stream inherits the properties of ios and declares input functions such get(), getline() and read().the extraction operator used for this >>

• ostream(output stream). This also inherits properties from ios and declared output functions such as put() and write(). It uses the insertion operator <<.

• iostream(input/output stream). This inherits properties from ios istream and ostream and through multiple inheritance contains all the input output functions.

iii). Access control: This is done using three keywords public, private and protected. These keywords are visibility labels. When the data members of a class are declared as private, then they will be visible only within the class. If we declare the class members as public then it can be accessed from the outside world also. Private specifier is used in data hiding which is the key feature of object oriented programming. The use of the keyword private is optional. When no specifier is used the data member is private by default. If all the data members of a class are declared as private then such a class is completely hidden from the outside world and does not serve any purpose. class class-name
{
private: int x,y;//No entry to private area private: int a,b;//entry allowed to public area
}

These access specifiers determine how elements of the base class are inherited by the derived class. When the access specifier for the inherited base class is public, all public members of the base class become public members of the derived class. If the access specifier is private, all public members of the base class become private members for the derived class. Access specifier is optional. In case of a derived ‘class’ it is private by default. In case of a derived ‘structure’ it is public by default.
The protected specifier is equivalent to the private specifier with the exception that protected members of a base class are accessible to members of any class derived from the base. Outside the base or derived class, protected members are not accessible. The protected specifier can appear anywhere in the class.
When a protected member of a base class is inherited as public by the derived class, it becomes protected member of the derived class. If the base is inherited a private, the protected member of the base becomes private member of the derived class.

iv) Friend:
Friend is keyword in C++ which is used to declare friend function and friend classes. It can access the private data members of the class it has to take the help of the object of that class. A friend function is not the member of the class. When we create an object memory is not located for the friend function. It is defined like a normal function. While calling a friend function we not use object as friend function is not the part of the object. Thus is called like any normal non member function. It also helps in operator overloading.
The following is an example program:
|#include<iostream.h> |void max(two s,one t) |
|using namespace std; |{ |
|class one; |if(s.a>=t.b) |
|class two |cout<<s.a; |
|{ |else |
|int a; |cout<<t.b; |
|public: |} |
|void setvalue(int n){a=n;} |int main() |
|friend void max(two,one); |{ |
|}; |one obj1; |
|class one |obj1.setvalue(5); |
|{ |two obj2; |
|int b; |obj2.setvalue(10); |
|public: |max(obj2,obj1); |
|void setvalue(int n){b=n;} |return 0; |
|friend void max(two,one); |} |
|}; | |

When we declare all the member functions of a class as friend functions of another then such a class is known as a friend class. class Z
{
friend class X;//all member functions af X are friends of Z
}

69. What is the difference between passing a parameter by reference and constant reference? (2)
Ans: By passing a parameter by reference, the formal argument in the function becomes alias to the actual argument in the calling function. Thus the function actually works on the original data. For example: void swap(int &a, int &b) //a and b are reference variables
{
int t=a; a=b; b=t;
}
The calling function would be: swap(m,n); the values of m and n integers will be swapped using aliases.
Constant Reference: A function may also return a constant reference. Example: int & max(int &x,int &y)
{
If((x+y)!=0) return x; return y;
}
The above function shall return a reference to x or y.

70. Define the following terms and give an example to show its realization in C++
(i) Encapsulation (ii) Class variables and class functions
(iii) Repeated inheritance (iv) Overloading (3.5 x 4)
Ans:
(i) Encapsulation: The term encapsulation is often used interchangeably with information hiding. Not all agree on the distinctions between the two though; one may think of information hiding as being the principle and encapsulation being the technique. A software module hides information by encapsulating the information into a module or other construct which presents an interface. A common use of information hiding is to hide the physical storage layout for data so that if it is changed, the change is restricted to a small subset of the total program. For example, if a three-dimensional point (x,y,z) is represented in a program with three floating point scalar variables and later, the representation is changed to a single array variable of size three, a module designed with information hiding in mind would protect the remainder of the program from such a change.
(ii) Class variables and class functions: Static variables are associated with the class rather than any class objects, so they are known as class variables. The type and scope of each class variable must be defined outside the class definition as they are stored separately rather than as a part of an object. Static functions can have access to only other static members (functions and variables) declared in the same class. These functions are known as class functions. A class function is called by using the class name instead of its objects like
Class-name:: function-name;
(iii)Repeated Inheritance: C++ requires that the programmer state which parent class the feature to use should come from. C++ does not support explicit repeated inheritance since there would be no way to qualify which superclass to use. Repeated inheritance means not being able to explicitly inherit multiple times from a single class. Multiple Inheritance usually corresponds to this-a relationship. It is a common mistake to use multiple inheritance for has-a relationship. For example, a Filter circuit may consist of Resistors, Capacitors and Inductors. It'll be a mistake to declare Filter as a subclass of resistor, capacitor and inductor (multiple inheritance). Instead, it is better to declare component objects of resistors, capacitors, and inductors within the new Filter class, and reference the component methods indirectly through these component objects.
(iv)Overloading: The process of making a function or an operator behave in different manners is known as overloading. Function overloading means the use of same function name to perform a variety of different tasks. The correct function to be invoked is selected by seeing the number and type of the arguments but not the function type.
Operator overloading refers to adding a special meaning to an operator. The operator doesn’t lose its original meaning but the new meaning is added for that particular class. For example, we can add two strings as:
String1+String2=string3;
“good”+ “girl”= “goodgirl”;
An example program of function overloading:
//Function volume is overloaded three times.
|#include<iostream.h> |int volume(int s) |
|using namespace std; |{ |
|int vol(int); |return(s*s*s); |
|double vol(double,int); |} |
|long vol(int,int,int); |double volume(double r,int h) |
|int main() |{ |
|{ |return(3.14519*r*r*h); |
|cout<<volume(2)<<"\n"; |} |
|cout<<volume(2.5,8)<<"\n"; |long volume(int l,int b,int h) |
|cout<<volume(2,3,5)<<"\n"; |{ |
|return 0; |return(l*b*h); |
|} |} |
| |The output would be: |
| |8 |
| |157.26 |
| |30 |

71. Define a class Point which is a three dimensional point having x, y and z coordinates. Define a constructor which assigns 0 if any of the coordinates is not passed. (6)
Ans:
#include <iostream.h>
#include<conio.h>
class Point { int X; int Y; int Z; public: Point() {X=Y=Z=0;}
Point(int x, int y, int z)
{ X=x; Y=y;Z=z;} int getX(){ return X;} int getY(){return Y;} int getZ(){return Z;}
};

72. Define a class Sphere which has a radius and a center. Use the class Point defined in (Q 112) to define the center. Define the constructor. Define a member function Volume (which is given as 3 r p ) which computes the volume. Use the class in main() to create an instance of sphere. Compute the volume and print it.(10)
Ans:
|class Sphere |void main() |
|{ |{ clrscr(); |
|int radius; |Point YourPoint(); |
|Point center; |Point p(3,4,5); |
|public: |Sphere s1(1,p); |
|Sphere(){} |s1.showdata(); |
|Sphere(int rad,Point &p) |float f=s1.volume(); |
|{ radius=rad; |cout<<"\nVolume="<<f; |
|center=p; |getch(); |
|} |} |
|void showdata() | |
|{ cout<<"Radius="<<radius; | |
|cout<<"\nCenter="<<"("<<center.getX()<<","<<center.getY()<<","<<center.get | |
|Z()<<")"; | |
|} | |
|float volume() | |
|{ return (3.14*radius*radius*radius); | |
|} | |
|}; | |

73. What is the access specification that should precede a friend function? (2)
Ans: The access specifier that should precede a friend function can be either public or private. The meaning and working of the friend function is not altered by using any of the two access specifiers.

Define a class Vector which can hold 20 elements of type int. Write a member function read() which reads the values from the input stream and assigns them to the Vector object.
(6)
Ans:
|#include<conio.h> | |
|#include<iostream.h> | |
|const size = 20; | |
|class vector | |
|{ | |
|int v[size]; | |
|public: | |
|vector(); | |
|void read(); | |
|vector(int *x); | |
|friend vector operator +(vector a, vector b); | |
|friend istream & operator >> (istream &, vector &); | |
|friend ostream & operator << (ostream &, vector &); | |
|}; | |
|vector :: vector() | |
|{ | |
|for(int i=0; i<size ; i++) | |
|v[i] = 0; | |
|} | |
|vector :: vector(int *x) | |
|{ | |
|for(int i=0; i<size; i++) | |
|v[i] = x[i]; | |
|} | |
|void vector :: read() | |
|{ | |
|int x[20]; | |
|cout<<"\nEnter 20 values"; | |
|for(int i=0;i<size;i++) | |
|cin>>x[i]; | |
|for(i=0; i<size; i++) | |
|v[i] = x[i]; | |
|} | |
| | |

74. Overload the operator + for the class Vector defined in Q115 above which adds two vectors. Define the addition operator as a friend function. The result must be returned as an object of the class Vector.(8)
Ans:
|vector operator +(vector a, vector b) |ostream & operator << (ostream&dout, vector&b) |
|{ |{ dout<<"("<<b.v[0]; |
|vector c; |for(int i=1;i<size;i++) |
|for(int i=0;i<size;i++) |dout << " , " << b.v[i]; |
|c.v[i] = a.v[i] + b.v[i]; |dout <<" ) "; |
|return c; |return(dout); |
|} |} |
|istream & operator >> (istream&x, vector&b) |void main() |
|{ |{ |
|for(int i=0;i<size;i++) |clrscr(); |
|x >> b.v[i]; |vector m; |
|return(x); |m.read(); |
|} |vector n; |
| |cout<< "enter elements of vector n"<<'\n'; |
| |cin>>n; |
| |cout<<'\n'; |
| |cout<<"m = "<<m<<'\n'; |
| |cout<<"\nn="<<n<<'\n'; |
| |vector p; |
| |p = m+n; |
| |cout<<'\n'; |
| |cout<<"p = "<<p<<'\n'; |
| |getch(); |
| |} |

75. An organization has two types of employees: regular and adhoc. Regular employees get a salary which is basic + DA + HRA where DA is 10% of basic and HRA is 30% of basic. Adhoc employees are daily wagers who get a salary which is equal to Number * Wage
(i) Define the classes shown in the following class hierarchy diagram:
(ii) Define the constructors. When a regular employee is created, basic must be a parameter. When adhoc employee is created wage must be a parameter.
(iii) Define the destructors.
(iv) Define the member functions for each class. The member function days ( ) updates number of the Adhoc employee.
(v) Write a test program to test the classes. (4+4+2+4+2)
Ans:
|#include<iostream.h> |class Adhoc : public Employee |
|#include<conio.h> |{ |
|#include<stdio.h> |float wage; |
|#include<stdlib.h> |int number; |
|#include<string.h> |public: |
|class Employee |Adhoc(float wg) |
|{ |{ |
|char name[25]; |wage=wg; |
|int eno; |number=0; |
|public: |} |
|Employee() |void days(int n) |
|{ |{ |
|strcpy(name, " "); |number+=n; |
|eno=0; |} |
|} |void salary() |
|void getdata() |{ |
|{ |//call Base class Showdata |
|cout<<endl<<"Name of Employee:-> "; |Employee::salary(); |
|cin>>name; |cout<<endl<<"Total Payble = "<<wage*number; |
|cout<<endl<<"Employee Number:-> "; |} |
|cin>>eno; |void getdata() |
|} |{ |
|void salary() |Employee::getdata(); |
|{ |} |
|cout<<endl<<eno<<'\t'<<name; |~Adhoc() |
|} |{ |
|~Employee() |} |
|{ |}; |
|} |void main() |
|}; |{ |
|class Regular : public Employee |class Regular robj(5000); |
|{ |class Adhoc aobj(65); |
|float Basic; |robj.getdata(); |
|public: |aobj.getdata(); |
|Regular(float bs) |aobj.days(25); |
|{ |cout<<endl<<"Details of Regular Employee1\n"; |
|Basic=bs; |robj.salary(); |
|} |cout<<endl<<"Details of Adhoc Employee1\n"; |
|void getdata() |aobj.salary(); |
|{ |getch(); |
|Employee::getdata(); |} |
|} | |
|void salary() | |
|{ | |
|//call Base showdata(); | |
|Employee::salary(); | |
|cout<<endl<<"Basic = "<<Basic; | |
|cout<<endl<<"DA = "<<Basic*0.1; | |
|cout<<endl<<"HRA = "<<Basic*0.3; | |
|cout<<endl<<"Total Payble = "<<(Basic + (Basic*0.1) + | |
|(Basic*0.3)); | |
|} | |
|~Regular() | |
|{ | |
|} | |
|}; | |

76. Explain the following:
(i) ios class (ii) setf( ) function
(iii) rdstate() function (iv) writing of objects to files (8)
Ans:
i. ios class: ios is the base class meant for istream(input sream), ostream(output stream) and iostream(input/output stream).ios is declared as the virtual base class so that only one copy of its members are inherited by the iostream. ii. setf() function: This function is used to specify format flags that can control the form of output display ( such as left-justification) and (right justification). The syntax is: setf(arg1,arg2); where arg1 is a formatted flag and arg2 is a bit field. iii. rdstate() function: ios::rdstate() const;
This function returns the current internal error state flags of the stream. The internal error state flags are automatically set by calls to input/output functions to signal certain types of errors that happened during their execution. It does not contain any parameter. iv. Writing objects to a file: C++ allows us to read from and write to the disk files objects directly. The binary function write() is used to write object to files. The function write copies a class object from memory byte to byte with no conversion. It writes only the data members and the member functions.

77. Write a program which asks for a file name from the keyboard, opens a file with that name for output, reads a line from the keyboard character by character and writes the line onto the file. (8)
Ans:
|#include<iostream.h> |ifstream in(name); |
|#include<stdio.h> |if (in==NULL) |
|#include<conio.h> |{ |
|#include<fstream.h> |cout<<endl<<"\nUnexpected Error."; |
|#include<stdlib.h> |getch(); |
|void main() |exit(1); |
|{ |} |
|cout<<endl<<"Enter the file name for output:-> "; |cout<<endl<<"U have entered following\n"; |
|char name[25]; |while(in) |
|cin>>name; |{ |
|ofstream out(name); |in>>ch; |
|if (out==NULL) |cout<<ch; |
|{ |} |
|cout<<endl<<"\nUnable to open file."; |in.close(); |
|getch(); |cout<<endl<<"Thanks"; |
|exit(1); |getch(); |
|} |} |
|char ch; | |
|cout<<endl<<"Press 'T' to terminate input.\n"; | |
|while(1) | |
|{ | |
|cin.get(ch); | |
|if (ch=='T')break; | |
|out.put(ch); | |
|} | |
|out.close(); | |

78. Differentiate between
(i) int* q = p; and n = *p;
(ii) Constructor and destructor
(iii) Interface and implementation of a class
(iv) public and private member of a class
(v) Overloaded pre-increment operator and overloaded post increment operator (vi) Abstract and concrete class
(vii) get ( ) and getline ( ) function
(viii) Composition and inheritance (16)
Ans:
(i) int* q=p; the value of p will be assigned to pointer q which will be treated as an address. int n=*p; in this an integer variable n is initialized with the value stored at the address to which the pointer p points.
(ii) A constructor is a member function which is used to initialize the data members of a class. It has the same name as that of the class. It does not have any return type and is invoked automatically on the creation of an object. test() //constructor for the class test
A destructor is a member function that is used to destroy the objects that’s have been created by the constructor. It frees the memory space for future use. It also has no return type but its declaration is preceded by a tilde.
~test(); //destructor function (iii) The keywords public and private are visibility labels. When the data members of a class are declared as private, then they will be visible only within the class. If we declare the class members as public then it can be accessed from the outside world also. Private specifier is used in data hiding which is the key feature of object oriented programming. The use of the keyword private is optional. When no specifier is used the data member is private by default. If all the data members of a class are declared as private then such a class is completely hidden from the outside world and does not serve any purpose.
(iv) In earlier version of C++ when an increment operator was overloaded there was no way of knowing whether the operator precedes or follows its operand. That is assuming that the two statement ob++ and ++ob had identical meanings. However the modern specification for C++ has defined a way through which compiler distinguishes between these operator. For this two versions were used. One defined as return-type class-name :: operator #( ) and the second is defined as rerurn-type class-name :: operator #(int notinuse). In (int notinuse) zero value is passed.
(v) In C++ an abstract class is one which defines an interface, but does not necessarily provide implementations for all its member functions. An abstract class is meant to be used as the base class from which other classes are derived. The derived class is expected to provide implementations for the member functions that are not implemented in the base class. A derived class that implements all the missing functionality is called a concrete class.
(vi) get() function extracts a character from the stream and returns its value (casted to an integer).The C++ string class defines the global function getline() to read strings from an I/O stream. The getline() function reads a line from is and stores it into s. If a character delimiter is specified, then getline() will use delimiter to decide when to stop reading data. Example: getline(cin, s);
(vii)The difference between inheritance and composition is the difference between “is-a” and “has-a”. For example, we would not design a “car” object to be inherited from “engine”, “chassis”, “transmission”, and so on (“car is-a engine” makes no sense). We would “compose” the car object from its constituent parts (“car has-a engine” makes a lot of sense). Once we start thinking in terms of “is-a” versus "has-a", it's a lot easier to do proper design.

79. Discuss the role of inheritance in object-oriented programming. What is public, private and protected derivation? (8)
Ans:
Inheritance: it is the property by which one class can be derived from another class such that it acquires the properties of its base class. Just like a child inherits the properties of its parents in the same way OOP allows us to reuse the members and functions of class to be derived by another class. There are many different kinds of inheritance like multiple inheritance, multilevel inheritance and hierarchical inheritance.
The visibility mode specified while declaring a derived class plays a very important role in the access control of the data members of the class. The visibility mode is one of the three keywords: public, private and protected. These access specifiers determine how elements of the base class are inherited by the derived class. When the access specifier for the inherited base class is public, all public members of the base class become public members of the derived class. If the access specifier is private, all public members of the base class become private members for the derived class. Access specifier is optional. In case of a derived ‘class’ it is private by default. In case of a derived ‘structure’ it is public by default. The protected specifier is equivalent to the private specifier with the exception that protected members of a base class are accessible to members of any class derived from the base. Outside the base or derived class, protected members are not accessible. The protected specifier can appear anywhere in the class. When a protected member of a base class is inherited as public by the derived class, it becomes protected member of the derived class. If the base is inherited a private, the protected member of the base becomes private member of the derived class.

80. Explain the meaning of polymorphism. Describe how polymorphism is accomplished in C++ taking a suitable example? (8)
[pic]

Polymorphism is the property of representing one operation into many different forms. One operation may express different in different situations. The process of making a function or an operator behave in different manners is known as overloading the function or the operator Polymorphism is one of the most useful features of object oriented programming. It can be achieved both at run time and at compile time. At compile time polymorphism is achieved using function overloading and operator overloading. At the time of compilation the compiler knows about the exact matching as to which function to call or invoke. This is known as compile time polymorphism or early binding. Polymorphism can also be achieved at run time. This is done using the concept of virtual functions. Which class function is to be invoked is decided at run time and then the corresponding object of that class is created accordingly. This is also called as late binding. The following example program explains how polymorphism can be accomplished using function overloading.
//Function volume is overloaded three times.
#include<iostream.h>
int volume(int); double volume(double,int); long volume(long,int,int); int main()
{
cout<<volume(10)<<"\n"; cout<<volume(2.5,8)<<"\n"; cout<<volume(100L,75,15)<<"\n"; return 0;
}
int volume(int s)
{
return(s*s*s);
}
double volume(double r,int h)
{
return(3.14519*r*r*h);
}
long volume(long l,int b,int h)
{
return(l*b*h);
}
The output would be:
1000
157.26
112500

81. Define a class Fraction whose objects represent rational numbers (i.e. fractions). Include integer data members num and den for storing the numerator and denominator respectively.
a. Write the following functions for fraction:
(i) parameterised constructors with one and two arguments.
(ii) copy constructors.
(iii) a function, eval-fract() for evaluating the value of the rational number.
(iv) a function, invert() for inverting the given rational number.
Ans:
a.
#include<conio.h>
#include<iostream.h> class fract
{
int num; int den; public: fract(int a); fract(int a,int b); fract(fract &); float eval_fract(); void invert(); void display();
};
fract::fract(int a)
{
num=den=a;
}
fract :: fract(int a,int b)
{
num=a; den=b; } fract :: fract(fract &f)
{
cout<<"copy constructor called\n"; num=f.num; den=f.den;
}
float fract :: eval_fract()
{
float res; res=(float)num/den; return res;
}
void fract ::invert()
{
int t=num; num=den; den=t;
}
void fract ::display()
{
cout<<num<<"/"<<den;
}
void main()
{
clrscr(); fract f1(2); f1.display(); cout<<"\n"; fract f3(2,3); fract f2=f3; float f=f2.eval_fract(); cout<<"The value of fraction is:"<<f<<"\n"; f2.invert(); f2.display(); getch(); }
b. Overload >> and << operators for reading and printing the fraction object from the keyboard. (2+8+6)
Ans: Function declared inside the class fract for overloading << and >> operator: friend istream & operator >> (istream &, fract &); friend ostream & operator << (ostream &, fract &);
Functions defined outside the class: istream & operator >> (istream&x, fract&b)
{
x >> b.num>>b.den; return(x); } ostream & operator << (ostream&dout, fract&b)
{ dout << b.num; dout <<" / "<<b.den; return(dout); }
Statements in main() to invoke overloading of << and >> are: cout<< "enter num and den of the fraction f"<<'\n'; cin>>f; cout<<'\n'; cout<<"fraction = "<<f<<'\n';

82. What do you mean by static variable and static function? Give an example?(5)
Ans: Static class member variables are used commonly by the entire class. It stores values. No different copy of a static variable is made for each object. It is shared by all the objects. It is just like the C static variables.
• It has the following characteristics:
• On the creation of the first object of the class a static variable is always initialized by zero.
• All the objects share the single copy of a static variable.
• The scope is only within the class but its lifetime is through out the program.
A static function is just like a static variable. a static function has the following properties:
• A function can access only the static variable where both belong to the same class.
• A static function is called using the class name directly and not the object like class-name :: function-name;
The example given below demonstrates the use of static variable ‘count’ and static function ‘display()’:
#include<iostream.h>
using namespace std; class demo
{
int num; static int count; public: void set(void)
{
num=++count;
}
void show(void)
{
cout<<"Number : "<< num<<"\n";
}
static void display(void)
{
cout<<"count : "<<count<<"\n";
}
}; int demo::count; int main()
{
demo d1,d2; d1.set(); d2.set(); demo::display();//accessing static function demo d3; d3.set(); d1.show(); d2.show(); d3.show(); return 0;
}
83. Describe the basic characteristics object-oriented programming. (3)
Ans: Object Oriented Programming (OOP) is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.
Following are the basic characteristics of Object Oriented Programming:
• Encapsulation: The wrapping up of data and functions into a single unit is called encapsulation. The data can only be accessed by the function with which they have been tied up and not by the outside world. It creates an interface between the object’s data and the program.
• Inheritance: It is the property by which one class can be derived from another class such that it acquires the properties of its base class. Just like a child inherits the properties of its parents in the same way OOP allows us to reuse the members and functions of class to be derived by another class. There are many different kinds of inheritance like multiple inheritance, multilevel inheritance and hierarchical inheritance.
• Polymorphism: Polymorphism is the property of representing one operation into many different forms. One operation may express different in different situations. The process of making a function or an operator behave in different manners is known as overloading the function or the operator.
• Data Abstraction: Abstraction is the method of representing only the essential features and only which is necessarily required by the user. The important and crucial data is encapsulated. 84. What do you mean by operator overloading? How unary and binary operators are implemented using the member and friend functions? (8)
Ans: When an operator is overloaded it doesn’t lose its original meaning but it gains an additional meaning relative to the class for which it is defined. We can overload unary and binary operators using member and friend functions. When a member operator function overloads a binary operator the function will have only one parameter. This parameter will receive the object that is on right of the operator. The object on the left side is the object that generates the call to the operator function and is passed implicitly by “this”. Overloading a unary operator is similar to overloading a binary operator except that there is only one operand to deal with. When you overload a unary operator using a member function the function has no parameter. Since there is only one operand, it is this operand that generates the call to the operator function. Overloading operator using a friend function: as we know that a friend function does not have a ‘this’ pointer. Thus in case of overloading a binary operator two arguments are passed to a friend operator function. For unary operator, single operand is passed explicitly. We cannot use a friend function to overload an assignment operator(=).

85. Explain the importance of using friend function in operator overloading with the help of an example. (4)
Ans: We can overload operators using both member function and friend functions. There are certain cases when we prefer using a friend function more than a member function. For examples suppose we wish to pass two different types of operands to the operator function, one of the operands may be an object and the other may be an integer. In case of overloading a binary operator:
A = ob + 4; or A = ob * 2;
The above statement is valid for both a member function and a friend function. But the opposite is not valid for a member function:
A = 4 + ob; or A = 2 * ob;
This statement is valid only in case of a friend function. This is because the left hand operand should be an object as it is used to invoke a member operator function.
The following program illustrates the use of a friend function:
#include<iostream.h>
class coord
{
int x,y; public: coord()
{
x=0;y=0;
}
coord(int i,int j)
{
x=i;y=j;
}
void get_xy(int &i,int &j)
{
i=x;j=y;
}
friend coord operator +(int n,coord ob);
}
coord operator +(int n,coord ob)
{
coord temp; temp.x= n + ob.x; temp.y= n + ob.y; return temp;
}
int main()
{
coord ob(5,3),obj; int x,y,n; obj = n + obj; obj.get_xy(x,y); cout<<"\n x = "<<x<<"\n y = "<<y; return 0;
}
86. Define a class Date with three variables for day, month and year.
a. Write the default and parameterised constructors,
b. Overload the operators <<,>> to read and print Date object,
c. Overload > to compare two dates.
d. Write the destructor that sets values to zero for all three variables. Define object of the class in main and call the above defined functions. (2+2+3+3+4+2)
Ans:
#include<iostream.h>
#include<conio.h>
class Date
{ int day,month,year; public: a. Date()
{ day=month=year=0;
}
Date(int d,int m,int y)
{ day=d; month=m; year=y;
}
Date(Date &d1)
{ day=d1.day; month=d1.month; year=d1.year;
}
b. friend istream & operator >> (istream &, Date &); friend ostream & operator << (ostream &, Date &);
c. friend int operator >(Date &, Date &);
d. ~Date(){day=month=year=0;}
};
istream & operator >> (istream&x, Date&b)
{
x >> b.day>>b.month>>b.year; return(x); } ostream & operator << (ostream&dout, Date&b)
{
dout<<b.day<<"/"<<b.month<<"/"<<b.year; return(dout); } int operator>(Date &d1, Date&d2)
{ if(d1.year>d2.year) return 1; else if(d1.year<d2.year) return 0; else { if(d1.month>d2.month) return 1; else if(d1.month<d2.month) return 0; else {if(d1.day>d2.day) return 1; else return 0;
}
}
}
void main()
{ clrscr();
Date d1(3,4,2005); cout<<d1; Date d2; cout<<"\n Enter day, month and year:\n"; cin>>d2; cout<<d2; if(d1>d2) cout<<"\nBigger date is:"<<d1; else cout<<"\nBigger date is:"<<d2; getch(); }
87. Define the class Student which has name (char name[20]) and age(int). Define the default constructor, member functions get_data() for taking the name and age of the Student, print() for displaying the data of Student. (5)
Ans:
include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
class Student
{
char name[20]; int age; public: Student()
{
strcpy(name,""); age=0; } void getdata()
{
cout<<endl<<"Enter Name:-> "; cin>>name; cout<<endl<<"Enter Age:-> "; cin>>age; } void print()
{
cout<<endl<<name<<'\t'<<age;
}
friend void sort(Student *s1,int N);
};
88. For the above defined class (of Q139) create an array of students of size N and write the friend function sort(Student arr[N]) which sorts the array of Students according to their age. (6)
Ans: void sort(Student *s1, int N)
{
Student temp; for(int i=0;i<N-1;i++) for(int j=N-1;j>i;j--)
{
if (s1[j].age < s1[j-1].age)
{ temp=s1[j]; s1[j]=s1[j-1]; s1[j-1]=temp;
}
} cout<<"\n Sorted Data is:\n"; for(i=0;i<N;i++) s1[i].print();
}
89. Create a file namely “STUDENT.DAT” for storing the above objects in sorted order. (5)
Ans:
void main()
{ Student obj[100]; int N,i,j; clrscr(); cout<<endl<<"Enter maximum number of records u want to enter:-> "; cin>>N; for (i=0;i<N;i++) obj[i].getdata(); cout<<endl<<"U have entered following records:"; for (i=0;i<N;i++) obj[i].print(); sort(obj,N); fstream inoutfile; inoutfile.open("STUDENT1.DAT",ios::ate|ios::in|ios::out|ios::binary); inoutfile.seekg(0,ios::beg); for(i=0;i<N;i++) inoutfile.write((char *) &obj,sizeof obj); getch(); }
90. Consider a publishing company that markets both book and audio cassette version to its works. Create a class Publication that stores the title (a string) and price(type float) of a publication. Derive the following two classes from the above Publication class: Book which adds a page count (int) and Tape which adds a playing time in minutes(float). Each class should have get_data() function to get its data from the user at the keyboard. Write the main() function to test the Book and Tape classes by creating instances of them asking the user to fill in data with get_data() and then displaying it using put_data(). (16)
Ans:
#include<conio.h>
#include<iostream.h>
#include<string.h> class Publication
{
protected: char title[20]; float price; public: virtual void get_data(){} virtual void put_data(){}
};
class Book:public Publication
{
int page_count; public: void get_data(); void put_data();
};
class Tape:public Publication
{
float play_time; public: void get_data(); void put_data();
};
void Book::get_data()
{
cout<<"\nTitle? "; cin.getline(title,20); cout<<"\nPrice? "; cin>>price; cout<<"\nPage_count"; cin>>page_count; } void Book::put_data()
{
cout<<"\nTitle: "<<title; cout<<"\nPrice: "<<price; cout<<"\nPage_count: "<<page_count;
}
void Tape::get_data()
{ cin.get(); cout<<"\nTitle? "; cin.getline(title,20); cout<<"\nPrice? "; cin>>price; cout<<"\nPlay_time?"; cin>>play_time; } void Tape::put_data()
{
cout<<"\nTitle: "<<title; cout<<"\nPrice: "<<price; cout<<"\nPlay_time:"<<play_time; } void main()
{
clrscr();
Book book1; cout<<"Please enter book details:\n"; book1.get_data(); Tape tape1; cout<<"Please enter Tape details:\n"; tape1.get_data(); Publication* list[2]; list[0]=&book1; list[1]=&tape1; cout<<"\n Book details:\n"; list[0]->put_data(); cout<<"\n\n Tape Details:\n"; list[1]->put_data(); getch();
}
91. Write short notes on the following:
(i) Nested class.
(ii) Scope resolution operator.
(iii) this pointer. (4*3=12)
Ans:
(i) Nested class:
Inheritance, one of the major features of OOP, is to derive certain properties of the base class in the derived class. A derived class can make use of all the public data members of its base classes. When one class is defined inside another class, it is known as containership or nesting. It is also one of the inheriting properties. We can thus imply that one object can be a collection of many different objects. Both the concepts i.e. inheritance and containership have a vast difference. Creating an object that contains many objects is different from creating an independent object. First the member objects are created in the order in which their constructors occur in the body. Then the constructor of the main body is executed. An initialization list of the nested class is provided in the constructor. In the following example the arglist is the list of arguments that is to be supplied when a gamma object is defined. These parameters are used to define the members of gamma. The arglist1 and arglist2 are meant for the constructors a and b respectively. class alpha{....}; class beta{....}; class gamma
{
alpha a; beta b; public: gamma(arglist): a(arglist1), b(arglist2)
{
//constructor body
}
};
(ii). Scope Resolution Operator:
The :: (scope resolution) operator is used to qualify hidden names so that we can use them. We can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. For example: int count = 0; int main(void) { int count = 0;
::count = 1; // set global count to 1 count = 2; // set local count to 2 return 0;
}
The declaration of count declared in the main() function hides the integer named count declared in global namespace scope. The statement ::count = 1 accesses the variable named count declared in global namespace scope. We also use the class scope operator to qualify class names or class member names. If a class member name is hidden, we can use it by qualifying it with its class name and the class scope operator. In the following example, the declaration of the variable X hides the class type X, but you can still use the static class member count by qualifying it with the class type X and the scope resolution operator.
#include <iostream> using namespace std; class X
{
public: static int count;
};
int X::count = 10; // define static data member int main ()
{
int X = 0; // hides class type X cout << X::count << endl; // use static member of class X
}
(iii) this pointer:
C++ contains a special pointer that is called ‘this’. ‘this’ is a pointer that is automatically passed to any member function when it is called and it is a pointer to the object that generates the call.
#include<iostream.h>
#include<string.h> class inventory
{
char item[20]; double cost; int on_hand; public: inventory(char *i,double c,int o)
{
strcpy(this_item, i); this->cost=c; this->on_hand=o;
}
void show()
};
void inventory::show()
{
cout<<this->item; cout<<this->cost; cout<<this->on_hand;
}
int main()
{
inventory ob("Wrench",495,4); ob.show(); return 0;
}
92. Define the following terms related to Object Oriented Paradigm:
Encapsulation, Inheritance, Polymorphism, Data Abstraction (12)
Ans: The following are the features of Object Oriented Programming:
• Encapsulation: The wrapping up of data and functions into a single unit is called encapsulation. The data can only be accessed by the function with which they have been tied up and not by the outside world. It creates an interface between the object’s data and the program.
• Inheritance: It is the property by which one class can be derived from another class such that it acquires the properties of its base class. Just like a child inherits the properties of its parents in the same way OOP allows us to reuse the members and functions of class to be derived by another class. There are many different kinds of inheritance like multiple inheritance, multilevel inheritance and hierarchical inheritance.
• Polymorphism: polymorphism is the property of representing one operation into many different forms. One operation may express different in different situations. The process of making a function or an operator behave in different manners is known as overloading the function or the operator.
• Data Abstraction: Abstraction is the method of representing only the essential features and only which is necessarily required by the user. The important and crucial data is encapsulated. 93. Declare a class to represent bank account of customers with the following data members:Name of the depositor, Account number, Type of account(S for saving and C for Current), balance amount. The class also contains member functions to do the following:
(i) To initialise the data member (ii) To deposit money (iii) To withdraw money after checking the balance (minimum balance is Rs.1000) (iv) To display the data members.
(6)
Ans:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
class bank
{
char name[25],type; long ac_no; float bal,amt; public: class bank *next; bank() { strcpy(name,” “); type=’ ‘ ; ac_no=0; bal=0; next=NULL; } void deposit()
{
cout<<endl<<”Amount to be deposited:-> “; cin>>amt; bal+=amt; cout<<endl<<”Amount deposited successfully”;
}
void withdraw()
{
cout<<endl<<”How much u want to withdraw:-> “; cin>>amt; if (bal-amt>=1000)
{
bal-=amt; cout<<endl<<”Withdraw Done”;
}
else
{
cout<<endl<<”Amount exceeds the Available I”; getch(); }
}
void showdata()
{
cout<<endl<<name<<’\t’<<ac_no<<’\t’;; if (type==’S’)cout<<”Saving”; else if (type==’C’)cout<<”Current”; cout<<’\t’<<bal; } int search(long x)
{
if (ac_no==x) return 1; else return 0;
}
void getdata();
};
void bank::getdata()
{
cout<<endl<<”Enter name of Account Holder:-> “; cin>>name; cout<<endl<<”Enter Account Number:-> “; cin>>ac_no; rep: cout<<endl<<”Enter type of Account S=Saving, C=Current):-> “; cin>>type; if (type!=’S’ && type!=’C’)
{
cout<<endl<<”Wrong Input”; getch(); goto rep;
}
cout<<endl<<”Enter Amount:-> “; cin>>bal; next=NULL;
}
void main()
{
class bank *bptr=NULL,*tmp=NULL,*counter=NULL; int i=0,found=0,ch=0; long acno=0; while (1)
{
clrscr(); cout<<endl<<”1.Add a new customer”; cout<<endl<<”2.View Customer Details”; cout<<endl<<”3.Deposite Amount”; cout<<endl<<”4.Withdraw Amount”; cout<<endl<<”5.Exit”; cout<<endl<<”Enter your choice:-> “; cin>>ch; switch (ch)
{
case 1: if (bptr==NULL)
{
bptr= new bank; if (bptr==NULL)
144
Code: AC11 Subject: OBJECT ORIENTED PROGRAMMING
{
cout<<endl<<”Memory Allocation Problem”; getch(); exit(1);
}
bptr->getdata();
}
else
{
tmp=new bank; if (tmp==NULL)
{
cout<<endl<<”Memory Allocation problem”; getch(); exit(1);
}
tmp->getdata(); for (counter=bptr;counter->next!=NULL;counter=counter->next); counter->next=tmp; } break; case 2: cout<<endl<<”Name\tAc. No.\tType\tBalance\n”; for (counter=bptr;counter!=NULL;counter=counter->next) counter->showdata(); getch(); break; case 3: cout<<endl<<”Enter the Account Number to Deposite:-> “; long acno; cin>>acno; for (counter=bptr;counter!=NULL;counter=counter->next)
{
found=counter->search(acno); if (found==1)
{
counter->deposit(); getch(); break;
}
} if (found==0)
{
cout<<endl<<”Account not exists”; getch(); } break; case 4: cout<<endl<<”Enter the Account Number to Withdraw:-> “; cin>>acno; for (counter=bptr;counter!=NULL;counter=counter->next)
{
found=counter->search(acno); if (found==1)
{
counter->withdraw(); break; }
}
if (found==0)
{
cout<<endl<<”Account not exists”; getch(); } break; case 5: exit(1); default: cout<<endl<<”Wrong Choice”;
}
} getch(); }
94. How is the working of member function different from friend function and a non member function? (6)
Ans: A member function, a non –member function and a friend function, all the three are entirely different from each other. A member function is that which is declared and defined inside the class. It has full access to the private data members of a class. We can directly access the data members without taking the help of the object. It is not the case with a friend function. Although it can access the private data members of the class it has to take the help of the object of that class. A friend function is not the member of the class. When we create an object of a class, memory is not allocated for the friend function. It is defined like a normal function. While calling a friend function we not use object as friend function is not the part of the object. Thus is called like any normal non member function. A non member function cannot access the private members of a class. It is not declared inside the class definition.

95. Explain a pure virtual function with an example. (4)
Ans: A pure virtual function has no definition related to the base class. Only the function prototype is included. To make a pure virtual function the following syntax is used: virtual return_type function_name(par_list) = 0; when a class contains atleast one pure virtual function then it is called an abstract class.
The following is an example program:
#include<iostream.h>
using namespace std; class area
{
double dim1,dim2; public: void set_area(int d1,int d2)
{
dim1=d1; dim2=d2; } void get_dim(double &d1,double &d2)
{
d1=dim1; d2=dim2; } virtual double get_area()=0;
};
class rectangle: public area
{
public: double get_area()
{
double d1,d2; get_dim(d1,d2); return d1*d2;
}
}; class triangle: public area
{
public: double get_area()
{
double d1,d2; get_dim(d1,d2); return 0.5*d1*d2;
}
}; int main()
{
area *p rectangle r; triangle t;
r.set_area(3.3,4.5);
t.set_area(4.0,5.0); p=&r; cout<<"\n the area of rectangle is "<<p->get_area()<<endl; p=&t; cout<<"\n area of triangle is "<<p->get_area()<<endl; return 0;
}

96. Discuss the various situations when a copy constructor is automatically invoked. (6)
Ans:
A copy constructor is invoked in many situations:
• When an object is used to initialize another in a declaration statement.
• When an object is passed as a parameter to a function.
• When a temporary object is created for use as a return value of a function.
A copy constructor only applies to initialization. It does not apply to assignment.
Class-name(const class name ob)
{
//body of copy constructor
}
When an object is passed to a function a bitwise copy of that objet is made and given to the function parameter that receives the object. However there are cases in which this identical copy is not desired. For example, if the object contains a pointer to allocated memory. The copy will point to same memory as does the original object. Therefore, if the copy makes a change to the content of this memory it will be changed for the original object too. Also when the function terminates the copy will be destroyed causing its destructor to be called.

97. What are the advantages and disadvantages of inline functions? (6)
Ans: Inline functions:
Advantage of an inline function is that they have no overhead associated with function call and return statements. This means that inline function can be executed much faster than the normal function.
The disadvantage of an inline function is that if they are too large and called regularly, program grows larger. For this reason, only short functions are declared as inline.

Define Rules for operator Overloading. Write a program to overload the subscript operator ‘[ ]’. (8)
Ans:
The rules for operator overloading are as follows:
• New operators are not created. Only the current operators are overloaded.
• The overloaded operator must have at least one operand of user defined type.
• We cannot alter the basic meaning of the operator.
• When binary operators are overloaded through a member function then the left hand operand is implicitly passed as and thus it must be an object.
• Unary operators when overloaded through member functions will not take any explicit argument. The subscript operator can be overloaded only by means of a member function:
#include<iostream.h>
const int size=5; class arrtype
{
int a[size]; public: arrtype()
{
int i; for(i=0;i<size;i++) a[i]=i;
}
int operator [](int i)
{
return a[i];
}
}; int main()
{
arrtype ob; int i; for(i=0;i<size;i++) cout<<ob[i]<<" "; return 0;
}

98. How is a class converted into another class? Explain with one example. (8)
Ans: C++ allows us to convert one class type to another class type. For example obj1 = obj2;
The conversion of one class to another is implemented using a constructor or a conversion function. The compiler treats both of them in the same manner. To decide which form to use depends upon where we want the type conversion function to be located in the source file or in the destination class.
#include<iostream.h>
using namespace std; class invent2; class invent1;
{
int code; int items; float price; public: invent1(int a,int b,float c)
{
code=a; items=b; price=c;
}
void putdata()
{
cout<<"Code : "<<code<<"\n"; cout<<"Items : "<<items<<"\n"; cout<<"Price : "<<price<<"\n";
}
int getcode(){return code;} int getitems(){return items;} float getprice(){return price;} operator float(){return (items*price);}
/*operator invent2()
{
invent2 temp; temp.code=code; temp.value=price*items; return temp;
}*/
}; class invent2
{
int code; float value; public: invent2()
{
code=0; value=0; } invent2(int x,float y)
{
code=x; value=y; } void putdata()
{
cout<<"Code : "<<code<<"\n"; cout<<"Value : "<<value<<"\n\n";
}
invent2(invent1 p)
{
code=p.getcode(); value=p.getitems()*p.getprice(); }
};
int main()
{
invent1 s1(115,9,178.6); invent2 d1; float total_value; total_value=s1; d1=s1; cout<<"\n Product details - invent1 type"<<"\n"; s1.putdata(); cout<<"\n Stock Value"<<"\n"; cout<<"\n Value = "<<total_value<<"\n"; cout<<"\n Protype details - invent2 type"<<"\n"; d1.putdata(); return 0;
}

99. How does visibility mode control the access of members in the derived class? Explain with an example. (6)
Ans:
The visibility mode specified while declaring a derived class plays a very important role in the access control of the data members of the class. The visibility mode is one of the three keywords: public, private and protected. These access specifiers determine how elements of the base class are inherited by the derived class. When the access specifier for the inherited base class is public, all public members of the base class become public members of the derived class. If the access specifier is private, all public members of the base class become private members for the derived class. Access specifier is optional. In case of a derived ‘class’ it is private by default. In case of a derived ‘structure’ it is public by default. The protected specifier is equivalent to the private specifier with the exception that protected members of a base class are accessible to members of any class derived from the base. Outside the base or derived class, protected members are not accessible. The protected specifier can appear anywhere in the class.
When a protected member of a base class is inherited as public by the derived class, it becomes protected member of the derived class. If the base is inherited a private, the protected member of the base becomes private member of the derived class.
Example:
#include<iostream.h> using namespace std; class one
{
int x; public: int y; void get_xy(); int get_x(void); void dis_x(void);
};
class two: public one
{
int z; public: void prod(void); void display(void);
};
void one:: get_xy(void)
{
x=7; y=9; } int one:: get_x()
{
return x;
}
void one::dis_x()
{
cout<<"x= "<<x<<"\n";
}
void two::prod()
{
z=y*get_x;
}
void two::display()
{
cout<<"x= "<<get_x()<<"\n";
152
Code: AC11 Subject: OBJECT ORIENTED PROGRAMMING cout<<"y= "<<y<<"\n"; cout<<"z= "<<z<<"\n";
}
int main()
{
two m;
m.get_xy();
m.prod();
m.dis_x();
m.display();
d.prod();
d.display(); return 0;
}

100. What is run time polymorphism? How it is achieved? Explain with an example? (4)
Ans: Polymorphism is one of the most useful features of object oriented programming.
Polymorphism means to have many forms of one name. it can be achieved both at run time and at compile time.
Polymorphism can also be achieved at run time. This is done using the concept of virtual functions. Which class’ function is to be invoked is decided at run time. And then the corresponding object of that class is created accordingly. This is also called as late binding. For this concept we always need to make use of pointers to objects.
The example illustrates the concept of virtual functions:
#include<iostream.h>
class base
{
public: int i; base(int x)
{
i=x;
}
virtual void func()
{
cout<<"\n using base version of function"; cout<<i<<endl; }
};
class derived: public base
{
public: derived(int x):base(x){} void func()
{
cout<<"\n using derived version"; cout<<i*i<<endl; }
};
class derived1: public base
{
public: derived1(int x): base(x){} void func()
{
cout<<"\n using derived1 version"; cout<<i+i<<endl; }
};
int main()
{
base *p; base ob(10); derived d_ob(10); derived1 d_ob1(10); p=&ob; p->func(); p=&d_ob; p->func(); p=&d_ob1; p->func(); return 0;
}

101. Define a class loan with Principle, Period and Rate as data members. Incr (float) is a member function, which increases the rate of interest by the parameter value. If rate of interest is same for all loans, use appropriate declarations and implement the class. (6)
Ans:
#include<iostream.h>
#include<conio.h>
class loan
{
float principle,rate; int period; public: loan(float f,int p)
{ principle=f; rate=0.15; period=p;
}
void Incr(int N)
{
rate=rate+N;
}
float calculatevalue(loan &l)
{
int year=1; float sum=l.principle; if(l.principle>5000) l.Incr(1); while(year<=period) { sum=sum*(1+rate); year=year+1; } return sum;
}
}; void main()
{ float amount; loan l1(6000,5); amount=l1.calculatevalue(l1); cout<<"\nAmount="<<amount; getch(); }

102. Write a program having a base class Student with data member rollno and member functions getnum() to input rollno and putnum() to display rollno. A class Test is derived from class Student with data member marks and member functions getmarks() to input marks and putmarks() to display marks. Class Sports is also derived from class Student with data member score and member functions getscore() to input score and putscore() to display score. The class Result is inherited from two base classes, class Test and class Sports with data member total and a member function display() to display rollno, marks, score and the total(marks + score). (12)
Ans:
#include<iostream.h>
#include<conio.h>
using namespace std; class student
{
protected: int roll_num; public: void get_num(int a)
{
roll_num=a;
}
void put_num(void)
{
cout<<"Roll number: "<<roll_num<<"\n";
}
}; class test: public student
{
protected: float marks; public: void get_marks(float m)
{
marks=m;
}
void put_marks(void)
{
cout<<"Marks obtained: "<<marks<<"\n";
}
}; class sports
{
protected: float score; public: void get_score(float s)
{
score=s;
}
void put_score(void)
{
cout<<"Score: "<<score<<"\n";
}
}; class result: public test,public sports
{
float total; public: void display(void)
{
total=marks+score; put_num(); put_marks(); put_score(); cout<<"Total score: "<<total<<"\n";
}
}; void main()
{
result stu; stu.get_num(12); stu.get_marks(87.6); stu.get_score(5.5); stu.display(); getch(); }

103. Explain the following functions(with example) for manipulating file pointers: seekg(),seekp(),tellg(),tellp(). (8)
Ans: A file pointer is used to navigate through a file. We can control this movement of the file pointer by ourselves. The file stream class supports the following functions to manage such situations.
• seekg ():moves get pointer (input) to a specified location.
• seekp ():moves put pointer (output) to a specified location.
• tellg ():gives the current position of the get pointer.
• tellp (): gives the current position of the put pointer.
For example: infile.seekg (10);will move the file pointer to the byte number 10. ofstream fileout; fileout.open(“morning”, ios::app); int p = fileout.tellp(); the above statements will move the output pointer to the end of the file morning and the value of p will represent the number of bytes in the file. seekg and seekp can also be used with two arguments as follows. seekg (offset, ref position); seekp (offset, ref position); where offset referes to the number of bytes the file pointer is to be moved from the location specified by the parameter ref position.

104. Explain the following:
i) Stream class hierarchy. iii) Abstract class (4*4=16)
Ans:
(i)
The above hierarchy of classes are used to define various streams which deals with both the console and disc files. These classes are declared in the header file iostream. Ios is the base for istream, ostream and iostream base classes. Ios is declared as a virtual base class so that only one copy of its members are inherited by the iostream. The three classes istream_withassign, ostream_withassign and iostream_withassign are used to add assignment operators to these classes. (iii) Abstract class:
When a class contains at least one pure virtual function, it is referred to as an abstract class. An abstract class is something which is to be hidden by people and on which modifications can be done in future. Since an abstract class contains at least one function for which no body exists, technically it can be considered as incomplete and therefore no object is created. Thus we can also define an abstract class as a class for which no object is created. We may conclude that an abstract class exists only to be inherited. We may still create pointer to an abstract class. In the following example, class area is an abstract class because it has a pure virtual function get_area().
#include<iostream.h>
using namespace std; class area
{
double dim1,dim2; public: void set_area(int d1,int d2)
{
dim1=d1; dim2=d2; } void get_dim(double &d1,double &d2)
{
d1=dim1; d2=dim2; } virtual double get_area()=0;
};

105. What are the benefits of object oriented programming? Explain. (8)
Ans:
Object Oriented Programming (OOP) is an approach that provides a way of modulating programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand.
The advantages of OOP are as follows:
• Function and data both are tied together in a single unit.
• Data is not accessible by external functions as it is hidden.
• Objects may communicate with each other only through functions.
• It is easy to add new data and functions whenever required.
• It can model real world problems very well.
• Though inheritance we can eliminate redundant code and extend the use of existing classes.
• The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.
• It is possible to have multiple instances of an object to co-exist without any interference.
• The data centric design approach enables us to capture more details of a model in implemented form.
• It is possible to map objects in the problem domain to those in the program.
• Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler.
• Software complexity can be managed.

106. Explain Inline functions and the situations where inline expansion may not work and why? (8)
Ans: Inline functions: Whenever we write functions, there are certain costs associated with it such as jumping to the function, saving registers, pushing arguments into the stack and returning to the calling function. To remove this overhead we write an inline function. It is a sort of request to the compiler. If we declare and define a function within the class definition then it is automatically inline. We do not need to sue the term inline.
Advantage of inline functions is that they have no overhead associated with function call or return mechanism.
The disadvantage is that if the function made inline is too large and called regularly our program grows larger. There are certain conditions in which an inline function may not work:
• If a function is returning some value and it contains a loop, a switch or a goto statement.
• If a function is not returning a value and it contains a return statement.
• If a function contains a static variable.
• If the inline function is made recursive.

107. Define a class Coord having two members type int as x and y. Use this class to define another class Rectangle which has two members of type Coord as UpperLeftCoord and BottomRightCoord. Define the constructors and member functions to get the length and breadth of rectangle. Write a global function which creates an instance of the class Rectangle and computes the area using the member functions. (10)
Ans:
#include <iostream.h>
#include<conio.h>
#include<math.h> class coord { int X; int Y; public: coord() {X=Y=0;} coord(int x, int y)
{ X=x; Y=y;} int getX(){ return X;} int getY(){return Y;}
//int getZ(){return Z;}
};
class rectangle
{
coord UpperLeftCoord; coord BottomRightCoord; public: rectangle(){} rectangle(coord &p1,coord &p2)
{ UpperLeftCoord=p1;
BottomRightCoord=p2;
} void showdata()
{
cout<<"UpperLeftCoordinate="<<"("<<UpperLeftCoord.getX()<<","<<UpperLeftCoord.getY(
)<<")";
cout<<"\nBottomLeftCoordinate="<<"("<<BottomRightCoord.getX()<<","<<BottomRightCoo rd.getY()<<")"; } int getLength()
{ return(abs(UpperLeftCoord.getX()- BottomRightCoord.getX()));
}
int getBreath()
{ return(abs(UpperLeftCoord.getY()- BottomRightCoord.getY()));
}
int Area()
{ return (getLength()*getBreath());
}
}; void main()
{ clrscr(); coord c1(2,4); coord c2(6,2); rectangle r1(c1,c2); r1.showdata(); int f=r1.Area(); cout<<"\nArea="<<f; getch();
}

108. Write a C++ program using classes and objects to simulate result preparation system for 20 students. (8)
The data available for each student includes:
Name (includes first, mid and last name each of size 20 characters), Rollno, Marks in 3 subjects. The percentage marks and grade are to be calculated from the following information Percentage marks grade
[pic]
Ans:
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<process.h> class students
{ struct name
{
char first[20],mid[20],last[20];
};
struct name e[20]; int rollno[20],marks[20][3],counter; int per[20]; char grade[20]; public: students(); void getdata(); void calculate(); void showdata();
};
students :: students()
{ counter=0; for (int i=0;i<20;i++)
{ strcpy(e[i].first,""); strcpy(e[i].mid,""); strcpy(e[i].last,""); rollno[i]=0; for (int j=0;j<3;j++) marks[i][j]=0; per[i]=0; grade[i]=' ';
}}
void students :: getdata()
{
cout<<endl<<"Enter First Name of the Student:-> "; cin>>e[counter].first; cout<<endl<<"Enter Middle Name of the Student:-> "; cin>>e[counter].mid; cout<<endl<<"Enter Last Name of the Student:-> "; cin>>e[counter].last; cout<<endl<<"Enter Roll Number of the student:-> "; cin>>rollno[counter]; cout<<endl<<"Enter the Marks in Subject 1;-> "; cin>>marks[counter][0]; cout<<endl<<"Enter the Marks in Subject 2;-> "; cin>>marks[counter][1]; cout<<endl<<"Enter the Marks in Subject 3;-> "; cin>>marks[counter][2]; per[counter]=(marks[counter][0]+marks[counter][1]+marks[counter][2])/3; if (per[counter]>=90 && per[counter]<=100) grade[counter]='A'; else if (per[counter]>=75) grade[counter]='B'; else if (per[counter]>=60) grade[counter]='C'; else if (per[counter]>=50) grade[counter]='D'; else grade[counter]='F'; counter++;
}
void students :: showdata()
{
cout<<endl<<"First\tMiddle\tLast Marks1 Marks2 Marks3 Percentage
Grade\n";
for (int i=0;i<counter;i++)
{
cout<<endl<<e[i].first; cout<<' '<<e[i].mid; cout<<' '<<e[i].last; cout<<' '<<rollno[i]; cout<<' '<<marks[i][0]; cout<<' '<<marks[i][1]; cout<<' '<<marks[i][2]; cout<<' '<<per[i]; cout<<' '<<grade[i];
}
} void main()
{ students obj1; int i,n; cout<<endl<<"Enter how many records u want to enter:-> "; cin>>n; if (!(n<=20))
{
cout<<endl<<"Maximum number of records can be 20\n"; getch(); exit(1);
}
for (i=0;i<n;i++) obj1.getdata(); cout<<endl<<"Records added successfully."; obj1.showdata(); getch();
}

109. Is it possible that a function is friend of two different classes? If yes, then how it is implemented in C++. (8)
Ans: Yes, it is possible that a function can be a friend of two classes. Member functions of one class can be friend with another class. This is done by defining the function using the scope resolution operator. We can also declare all the member functions of one class as the friend functions of another class. In fact we can also declare all the member functions of a class as friend. Such a class is then known as friend class. The following program shows how a friend function can be a friend of two classes:
#include<iostream.h>
using namespace std; class one; class two
{
int a; public: void setvalue(int n){a=n;} friend void max(two,one);
};
class one
{
int b; public: void setvalue(int n){b=n;} friend void max(two,one);
};
void max(two s,one t)
{
if(s.a>=t.b) cout<<s.a; else cout<<t.b; } int main()
{
one obj1; obj1.setvalue(5); two obj2; obj2.setvalue(10); max(obj2,obj1); return 0;
}

110. Write a program to overload << and >> operator to I/O the object of a class. (8)
Ans:
#include<iostream.h> class complex
{
double real,imag; public: complex()
{
} complex(double r,double i)
{
real=r; imag=i; } friend ostream& operator <<(ostream& s,complex& c); friend istream& operator >>(istream& s,complex& c);
};
ostream& operator <<(ostream& s,complex& c)
{
s<<"("<<c.real<<","<<c.imag<<")"; return s;
}
istream& operator >>(istream& s,complex& c);
{
s>>c.real>>c.imag; return s;
}
void main()
{
complex c1(1.5,2.5),c2(3.5,4.5),c3; cout<<endl<<"c1= "<<c1<<endl<<"c2= "<<c2; cout<<endl<<"Enter a complex number: "; cin>>c3; cout<<"c3= "<<c3;
}

111. What is the difference between a virtual function and a pure virtual function? Give example of each. (8)
Ans: Virtual functions are important because they support polymorphism at run time. A virtual function is a member function that is declared within the base class but redefined inside the derived class. To create a virtual function we precede the function declaration with the keyword virtual. Thus we can assume the model of “one interface multiple method”. The virtual function within the base class defines the form of interface to that function. It happens when a virtual function is called through a pointer.
The following is an example that illustrates the use of a virtual function:
#include<iostream.h>
using namespace std; class base
{
public: int i; base(int x)
{
i=x;
}
virtual void func()
{
cout<<"\n using base version of function"; cout<<i<<endl; }
};
class derived: public base
{
public: derived(int x):base(x){} void func()
{
cout<<"\n sing derived version"; cout<<i*i<<endl; }
};
class derived1: public base
{
public: derived1(int x): base(x){} void func()
{
cout<<"\n using derived1 version"; cout<<i+i<<endl; }
};
int main()
{
base *p; base ob(10); derived d_ob(10); derived1 d_ob1(10); p=&ob; p->func(); p=&d_ob; p->func(); p=&d_ob1; p->func(); return 0;
}

A pure virtual function has no definition related to the base class. Only the function prototype is included to make a pure virtual function the following syntax is used: virtual return_type function_name(par_list) = 0;
The following is an example program:
#include<iostream.h>
using namespace std; class area
{
double dim1,dim2; public: void set_area(int d1,int d2)
{
dim1=d1; dim2=d2; } void get_dim(double &d1,double &d2)
{
d1=dim1; d2=dim2; } virtual double get_area()=0;
};
class rectangle: public area
{
public: double get_area()
{
double d1,d2; get_dim(d1,d2); return d1*d2;
}
}; class triangle: public area
{
public: double get_area()
{
double d1,d2; get_dim(d1,d2); return 0.5*d1*d2;
}
}; int main()
{
area *p rectangle r; triangle t;
r.set_area(3.3,4.5);
t.set_area(4.0,5.0); p=&r; cout<<"\n the area of rectangle is "<<p->get_area()<<endl; p=&t; cout<<"\n area of triangle is "<<p->get_area()<<endl; return 0;
}
Q.169 Write a program for Conversion from Basic to Class Type. (8)
Ans:
#include<iostream.h> class time
{
int hours; int minutes; public: time(){} time(int t)
{ hours=t/60; minutes=t%60; } void showtime()
{ cout<<hours<<"hrs "<<minutes<<"min";
}
}; void main()
{
time t1; int duration=90; t1=duration; t1.showtime();
}

112. How does inheritance influence the working of constructor and destructor?
Given the following set of definitions
Class x
{
}; class y: public x
{
}; class z: public y
{
}; z obj;

113. What order will the constructor and destructor be invoked? (8)
Ans: Inheritance has a great deal of influence over the working of constructors and destructors. In case of inheritance the base class constructor is invoked first and then the derived class constructor. In case of multiple inheritance, the constructors of base classes are executed in the order in which they occur in the declaration in the derived class. Similarly in case of multilevel inheritance, the base class constructors are executed in the order of their inheritance. Destructors in case of inheritance are executed exactly in the opposite order in which constructors are executed. Likewise in case of multilevel inheritance destructors are executed in the reverse of that is, from derived to base. class x
{
}; class y: public x
{
}; class z: public y
{
}; z obj;
In the above definitions, the contructor will be fired in the following sequence- class x _ class y _ class z similarly, destructors will be fired exactly in the reverse sequence- class z _ class y _ class x

115. What is meant by a constant member function? How is it declared? Give an example.(8)
Ans: Constant Member functions : A const member function is that which does alter the value of any data in the program. It is declared as follows: void area(int, int) const; float dis() const;

when a const function tries to alter any data ,the compiler generates an error message.

116. Write a program to create a database of the students information such as name, roll no and the program should have the following facilities. (10)
i) Adds a new records to the file. ii) Modifies the details of an record.
Displays the contents of the file.
Ans:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<fstream.h>
#include<stdlib.h>
#include<iomanip.h> class Students
{
int rollno; char name[25]; public: void getdata()
{
cout<<endl<<"Enter Name:-> ";cin>>name; cout<<endl<<"Enter Roll Number:-> ";cin>>rollno;
}
void showdata()
{
cout<<setw(10)<<rollno<<setw(10)<<name<<endl;
}
}; void main()
{
clrscr(); int r; fstream file; file.open("Student.TXT",ios::ate|ios::in | ios::out|ios::binary); file.seekg(0,ios::beg); Students obj; char ch; while (1)
{
cout<<endl<<"1.Add\n2.Modify\n3.Display\n4.Exit\nEnter your choice:-> "; cin>>ch; switch (ch)
{
case '1': obj.getdata(); file.write((char *) & obj, sizeof(obj)); break; case '2': int last = file.tellg(); int n = last/sizeof(obj); cout<<"number of objects = "<< n << '\n'; cout<<"total bytes in the file = "<<last<<'\n';
//modify the details of an item cout<<"enter object no. to b updtd \n"; int object; cin>>object; cin.get(ch); int location = (object - 1)*sizeof(obj); if(file.eof()) file.clear(); file.seekp(location); cout<<"enter new values of object \n"; obj.getdata(); cin.get(ch); file.write((char *)&obj,sizeof obj)<<flush; file.seekg(0); break; case '3': file.seekg(0); while(file.read((char *) &obj,sizeof obj)) obj.showdata(); break; case '4': exit(0); default: cout<<endl<<"Input out of reange.";
}
}
}

Similar Documents

Free Essay

C++ Objects Solutions

...C++ LOCATION OF VIDEONOTES IN THE TEXT Chapter 1 Designing a Program with Pseudocode, p. 19 Designing the Account Balance Program, p. 24 Predicting the Output of Problem 30, p. 24 Solving the Candy Bar Sales Problem, p. 25 Using cout to Display Output, p. 32 Assignment Statements, p. 59 Arithmetic Operators, p. 61 Solving the Restaurant Bill Problem, p. 72 Using cin to Read Input, p. 75 Evaluating Mathematical Expressions, p. 81 Combined Assignment Operators, p. 102 Solving the Stadium Seating Problem, p. 151 Using an if Statement, p. 162 Using an if/else Statement, p. 172 Using an if/else if Statement, p. 175 Solving the Time Calculator Problem, p. 236 The while Loop, p. 249 The for Loop, p. 263 Nested Loops, p. 277 Solving the Ocean Levels Problem, p. 299 Defining and Calling Functions, p. 306 Using Function Arguments, p. 316 Value-Returning Functions, p. 326 Solving the Markup Problem, p. 380 Creating a Class, p. 391 Creating and Using Class Objects, p. 393 Creating and Using Structures, p. 436 Solving the Car Class Problem, p. 480 Accessing Array Elements, p. 487 Passing an Array to a Function, p. 517 Two-Dimensional Arrays, p. 526 Solving the Chips and Salsa Problem, p. 567 Performing a Binary Search, p. 580 Sorting a Set of Data, p. 587 Solving the Lottery Winners Problem, p. 616 (continued on next page) Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 LOCATION OF VIDEONOTES IN THE TEXT Chapter 10 Pointer Variables...

Words: 11246 - Pages: 45

Free Essay

Snnsnjs

... COLLIGATIVE PROPERTIES OF SOLUTIONS Section Review Objectives • Identify the three colligative properties of solutions • Describe why the vapor pressure, freezing point, and boiling point of a solution differ from those properties of the pure solvent. Vocabulary • colligative properties • freezing-point depression • boiling-point elevation Part A Completion Use this completion exercise to check your understanding of the concepts and terms that are introduced in this section. Each blank can be completed with a term, short phrase, or number. In a solution, the effects of a nonvolatile _______ on the properties of the solvent are called _______. They include _______ point and vapor pressure _______, and boiling point _______. In each case, the magnitude of the effect is _______ proportional to the number of solute molecules or ions present in the _______. Colligative properties are a function of the number of solute _______ in solution. For example, one mole of sodium chloride produces _______ as many particles in solution as one mole of sucrose and, thus, will depress the freezing point of water _______ as much. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Part B True-False Classify each of these statements as always true, AT; sometimes true, ST; or never true, NT. 11. When added to 1000 g of water, 2 moles of a solute will increase the boiling point by 0.512°C. 12. One mole...

Words: 483 - Pages: 2

Free Essay

Speech 203

... * Has no secretary The most important problem would be catching the flight for the meeting in Chicago since it’s an emergency and work related. Solutions: Getting work done for the day on the air plane on the way to the meeting. Call the secretary to find out at least some of the info for the meeting. Item#2 Problems: * Internal politicking in the company * Finding someone to replace F.T. Dickenson * Dealing with eliminating his overtime hours The two most important problems would the politicking, because someone else may feel the same way and decide to leave the company too. Also, finding someone to replace him and do his unfinished work in such a short period of time. Solution: Search for a new employee ASAP. Item#3 Problems: * Workers threatening to walk out over a co-worker * 10 votes to dismiss Foreman Edward George The workers are the most important asset to the company, so their interest should be first. Second, you have to figure out what to do about the votes to dismiss Ed George. Solutions: Talk to Ed George about his problems with his co-workers. Hold a meeting and get even more workers involved in the voting process, the take another vote. Item#4 Problems: * Overloading which can result in interruption of electrical power. * Not being reachable for Southern Power Solution: Contact Southern Power ASAP. See if they could come out and help with the problem. Item#5 Problem: * Balancing your work and his until Wednesday ...

Words: 922 - Pages: 4

Free Essay

Science

...Detailed Lesson Plan (Grade 7) 1. Objectives After providing the necessary materials, each student; 1.1 investigates the different types of solutions: -unsaturated -saturated -supersaturated 1.2 performs an actual activity about solubility. 1.3 values the common solutions that can be found at home and can be used in daily living. 1. Learning Tasks 2.1 Topic: Solutions 2.2 Concept: The unsaturated solution has a less amount of solute to be dissolved. The saturated solution can hold no more solute to be dissolved. The supersaturated solution cannot hold more solute. 2.3 Materials 2.3.1 Textbook/Other Reference -Science Grade 7: Matter (K-12 Curriculum), pages 1-16 - http://www.infoplease.com/encyclopedia/science/solution-heat-solution.html 2.3.2 Instructional Materials - video clips, materials enumerated for the experiment and activity sheet. 2. Methodology 3.1 Daily Activities 3.1.1 Prayer/ Greetings Christ Jesus Whom we open our eyes, may you be there; When we open our ears, may you be there; When we open our mouths, may you be there; When we open our diaries, may you be there. Help us to see with your eyes; Help us to hear with your ears; Help us to speak your truth in love; Help us to make time for you… for others… for ourselves. Amen. 3.1.2 Checking of Attendance 3.1.3 Checking of Assignment 3.2 Preparatory Activities 3.2.1 Review Teacher: Class...

Words: 1391 - Pages: 6

Premium Essay

Recrystallization Report

...is successfully performed.2,3 Recrystallization works based on the difference in solubility when the temperature changes. Therefore, picking the solvent to dissolve the compound is a very tricky and important part. For single-solvent recrystallization, which is performed in this experiment, the chosen solvent should not dissolve the sample while cold, so that the crystal can be formed when the temperature drops. However, the solvent should dissolve the sample completely while hot in order to release all the impurity crystals being trapped up in the solid form of the desired compound. Furthermore, the impurities should have higher solubility than the desired compound in that chosen solvent, so that all the impurities would remain in the solution while recrystallization takes place.2,3 In case no single solvent can be found, a system of two solvents can also be used for recrystallization. Generally speaking, in this solvent pair, one of them can completely dissolve the sample while the other one cannot dissolve the sample at all. The primary requirement when making this system is that the two chosen solvents have to be completely miscible, in other words, can mix with each other in all proportions. After this requirement is satisfied, all students need to do is to find out the right proportion for the system.1,2,3...

Words: 2513 - Pages: 11

Free Essay

Spring 2013

...using MLA format. Lesson 1: Introduce the environment. Lesson 2: Identify the problem. Lesson 3: Identify the solutions. (What tools are available to perform the project?) Lesson 4: Evaluate the solutions. (If there are assumptions, what are they?) Lesson 5: Evaluate the ethical and social issues. (What ideas are compatible or incompatible with the problem and solutions?) Lesson 6: Propose the best solution. Lesson 7: Conclude your project experience. B. Write one paragraph for each of the above lessons. The lessons are directed to someone who has no experience in the field. Each lesson should be completed by the assigned due date. One Time Development: (This is a combination of the ongoing task.) A. In a term paper format (two+ pages), provide a formal proposal for the project analyzing the following (bring together all the lessons you worked on throughout the course): 1. The Problem 2. The Solutions Identified 3. The Solutions Evaluated 4. The Ethical and Social Issues 5. The Best Solution B. This paper will be traded with one assigned group member after receiving my feedback for editing improvements. Each student will read the assigned proposal, name 3 positive comments, ask 3 questions, and give 3 recommendations for their classmate. C. The final paper will be submitted to me via email, which I will provide instructions on how to do so later during the semester. Due...

Words: 293 - Pages: 2

Premium Essay

Essays

...place the list in order from weakest to strongest solute-solvent attraction. Some pairs may experience more than one type of force. a. water dissolved in ammonia b. NO dissolved in H2S c. CO2 dissolved in ammonia d. Mg(NO3)2 dissolved in water 2. At sea level, the partial pressure of O2 is 0.21 atm. However, the Dead Sea is not at sea level -- it’s at a much lower altitude, where the atmospheric pressure is 806 mmHg and the temperature is 20˚C. Use Henry’s Law and Table 13.2 to calculate the molar concentration of O2 in the Dead Sea. 3. Suppose we make a solution by dissolving 42.5 g of I2 in 1.50 mol of CCl4. a. What is the molality of this solution? b. Suppose we wanted to use our 42.5 g of I2 to make a 0.500 m solution. What volume of CCl4 would we need? The density of CCl4 is 1.589 g/mL. 4. We dissolve 200.0 g of NaCl in 684.5 g of water and find that the density of the solution is 1.15 g/mL. Calculate: a. The % by mass of NaCl b. The mole fraction of NaCl c. The molarity of NaCl d. The molality of NaCl 5. Calculate the number of moles of solute in each solution. a. A solution of Br2 dissolved in 50.0 g of...

Words: 741 - Pages: 3

Premium Essay

Kasikorn Bank Innovation Case Study (Thai Language)

...Project Present By 1. Atthaya Pancharin 53441642 2. Korntatan Patarataweetip 53441602 3. Panchabhorn Bodhintrsopon 53441617 4. Pikul Sithichan 53441620 5. Varatip Silapapong 53441625 May 2011 สารบัญ ประวัติความเป็นมา 3 ความหมายของตราสัญลักษณ์รวงข้าว 3 ความหมายของสีในสัญลักษณ์ ของธนาคารกสิกรไทย 4 ภารกิจ 4 วิสัยทัศน์ 4 ค่านิยมหลัก 4 นวัตกรรม กับธนาคารกสิกรไทย ตั้งแต่อดีตจนถึงปัจจุบัน 5 สรุป นวัตกรรมต่างๆของธนาคารกสิกรไทย 15 นวัตกรรมของธนาคารกรุงเทพ 19 บทวิเคราะห์ 20 จุดเปลี่ยนธนาคารกสิกร ผู้นำนวัตกรรมการเงิน 20 การสร้าง Positioning 24 กลยุทธ์การบริหาร Strategic Management 26 ตารางการเปรียบเทียบสินทรัพย์รวม และกำไรสุทธิ ของธนาคารกสิกรไทย และธนาคารกรุงเทพ ระหว่างปี 2549-2553 29 ข้อเสนอในการทำ Innovation เพิ่ม/ลด/เปลี่ยน 30 วิธีการวางแผนและ ดำเนินงานภายในกลุ่ม 31 วิธีการค้นหาข้อมูลต่างๆ 31 แหล่งข้อมูลที่ใช้ในการค้นหา 32 แผนการดำเนินการ 32 ประวัติความเป็นมา ธนาคารกสิกรไทย ก่อตั้งเมื่อวันที่ 8 มิถุนายน พ.ศ. 2488 ด้วยทุนจดทะเบียน 5 ล้านบาท และพนักงานชุดแรกเริ่มเพียง 21 คน มีอาคารซึ่งเป็นสาขาสำนักถนนเสือป่าในปัจจุบันเป็นที่ทำการแห่ง แรก การดำเนินงานของธนาคารประสบความสำเร็จเป็นอย่างดี เพียง 6 เดือน หรือเพียงงวดบัญชีแรกที่สิ้นสุด ณ วันที่ 31 ธันวาคม พ.ศ. 2488 มียอดเงินฝากสูงถึง 12 ล้านบาท มีสินทรัพย์ 15 ล้านบาท จากจุดที่เริ่มต้นจนถึงวันนี้ ธนาคารกสิกรไทยเติบโตอย่างมั่นคง ณ วันที่ 31 มีนาคม พ.ศ. 2554 มีทุนจดทะเบียน 30,486 ล้านบาท มีสินทรัพย์จำนวน 1,677,862 ล้านบาท เงินรับฝากจำนวน 1,182,390 ล้านบาท...

Words: 1501 - Pages: 7

Premium Essay

AP Biology: Diffusion And Osmosis

...within the bag equal to the concentration outside the bag. The glucose solution moved out of the bag making glucose present in the beaker. The glucose moved to make the solute concentration inside and out equal. If the initial and final % concentration of glucose and IKI for in the bag and in the beaker were given they...

Words: 1292 - Pages: 6

Premium Essay

Nt1310 Unit 2 Lab Report

...Q1 - Absorbance of Cyanocobalamin Vitamin B12 at wavelength 460 nm was 0.336 - Absorbance of Cyanocobalamin Vitamin B12 at wavelength 620 nm was 0.018 - The Concentration of Cyanocobalamin Vitamin B12 was 0.2 Molar Absorptivity In order to calculate the molar absorptivity I used the following equation : -Absorbance = 0.336 -L = 1 -Concentration = 0.2 ε = A / l x c so 0.336 / 1 x 0.2 = 0.0672 …. The molar absorptivity of the wavelength 460nm was 0.0672 - Likewise, the wavelength 620 has been calculated using the same equation: - A (Absorbance) = 0.018 - L = 1 - C Concentration = 0.2 ε = 0.018 / 1 x 0.2 = 0.0036, Therefore the molar absorptivity of the 620nm wavelength is 0.0036. Calculating the concentration To work out the concentration...

Words: 1100 - Pages: 5

Free Essay

Goods Hands Healthcare

...case several times. Do not just copy sentences from the case. Instead, express in your own words the essence of the case. 4. A list of what you think are the 10-15 most important facts/factors in the case. 5. The most important health administration problem/issue to be solved in the case. [1 sentence]. List other secondary problems in the case.  6. Your recommended solution for the case (a.-d. below). Make clear specific realistic recommendations. There must be a clear logical sequence to your thoughts and recommendations. (2-3 Pages) a. At least three possible realistic alternative solutions for the most important problem (stated above for 5) b. Criteria to evaluate possible alternative solutions. For example: acceptability to stakeholders, needed resources, legality, timing, cost-effectiveness, ability to implement, side effects, qualifications, statistical data, financial data, ethical considerations, fit with case facts, likelihood of actually solving the problem, etc.  c. Evaluation of the possible alternative solutions (6a) using the criteria (6b). (2 pages) d. Your recommended solution for the problem, based on 6a, 6b, and 6c. Justify your recommendation. 7. Specific MBA/MHA tools, methods, techniques, principles, theories, models, etc. from MBA courses that you used for this case. List specific tools (e.g Risk Management, Do not list general subjects (e.g., finance, leadership). 2-3 sentence explanations * SWOT Analysis, * Community Need Assessment...

Words: 295 - Pages: 2

Free Essay

Colligative Properties: Freezing Pointdepression and Molar Mass

...COLLIGATIVE PROPERTIES: FREEZING POINT DEPRESSION AND MOLAR MASS: AIM The aim of the experiment is to become familiar with the colligative properties and to use them to determine the molar mass of a substance. THEORY A solution consists primarily of solvent and therefore, most of the solution’s properties reflect the solute’s properties. The physical properties that the solution and solute do not share are known as colligative properties and they depend solely on the solute concentration. Some of these properties include vapor pressure lowering, boiling-point elevation, freezing point lowering, and osmotic pressure. The solvent boils when the vapor pressure, or tendency of solvent molecules to escape, is equivalent to the atmospheric pressure. At this moment, the gaseous and liquid states of the solvent are in dynamic equilibrium and the molecules change from the liquid to the gaseous states and from the gaseous to liquid states at equal rates. The dissolution of a solute with very low vapor pressure, or a nonvolatile solute, raises the boiling point and lowers the freezing point. Similarly, anti-freeze lowers the freezing point and lowers the boiling point. The colligative-property law describes these effects, stating that the "freezing point and boiling point of a solution differ from those of the pure solvent by amounts that are directly proportional to the molar concentration of the solute" (Brown, 203-204). The colligative-property law can be expressed using the equation: D T =...

Words: 1635 - Pages: 7

Free Essay

Lab Report Design Example

...Potassium Chloride in Water Research question How does temperature affect the solubility of potassium chloride in water? Hypothesis As the temperature of water increases, the particles of solid Potassium chloride, KCl, which are absorbing energy from its surrounding, start moving more easily between the solution and its solid state because. According to the second law of thermodynamics, the particles will shift to the more disordered, more highly dispersed solution state. I predict that as the temperature of a KCl and water mixture increases, then the solubility of the KCl will also increase. Variables Dependant variable The dependant variable will be the solubility of Potassium chloride in water that will be calculated at different temperatures. The solubility will change as temperature increases. Independent variable The control variables need to be constant in order to get valid and accurate results. The temperature of the solutions. Controlled variables The volume of distilled water used to dissolve Potassium chloride in each beaker The amount of Potassium chloride deposited into each beaker. The volume of the solution extracted by the syringe. Weight of each 50ml beaker Materials 6 Syringes 1 Heating plate 6 distinctly labeled 50ml Beakers 1 Electric Balance 6 Stirring Rods Distilled Water 6 distinctly labeled 100ml Beaker Controlling the variables The mass of Potassium chloride and the volume of distilled...

Words: 883 - Pages: 4

Free Essay

Solutions to Grooming Teens for Adulthood

...Solutions to Grooming Teens for Adulthood Reasoning and Problem Solving CST 1 November 30, 2009 To solve a problem one must often dive beneath the surface of the reflected obvious to reveal the rest of the issue hidden in the depths below. In Task one for this course the question of what is the best way to prepare teen’s for a successful adulthood has been addressed through several viewpoints and approaches. Just as there are multiple approaches in rearing children, there does not appear to be a single solution to the problem. Upon investigation it quickly becomes apparent that various groups can look at the same issue and will ultimately form different solutions that reflect their own skew on the problem. A closer look at example solution’s utilizing life skills through school settings, community resources, and Socratic home environments will demonstrate this concept. As an educator I believe that preparation is gleaned through understanding and understanding is gleaned from education. My solution would involve taking an active approach in educating the future educator by preparing the young to facilitate life skills for themselves and their own children one day. Equipping children with life applications of what they potentially will face as an adult is much like training a soldier for battle. Our county does not expect our military personnel to enlist and not receive training for what they will expect to encounter. Our children should not...

Words: 3075 - Pages: 13

Free Essay

Velocity

...i.e. solutions are not clear cut. These cases were real-life situations encountered by corporations. Since solutions were not clear cut, corporations approached accounting firms for guidance. Deloitte, Touche & Tohmatsu used these issues to compile a series of cases to provide students the opportunities to have a “hands-on” experience in how accounting firms go about looking for a solution. To assist students in completing the assignment, sample cases with solutions were posted. Students would need to use FASB Codification database (the same one used by accounting firms). You can access the database through: http://aaahq.org/ascLogin.cfm Userid: AAA52120 Password: 6HxBPpx The main purposes of the cases are: 1. Provide hands-on experience in using FASB Codification to research for accounting solutions. 2. Encourage team effort to examine possible solutions and come to a consensus well supported by accounting rules and pronouncements. There are many solutions to the cases, some better (or more in line with the pronouncements) than others. I look forward to your explorations with untainted young minds to come up with mesmerizing solutions. Any consultation with the instructor could bias your approach. It may even mislead the team to think that the discussion is about “the solution” and therefore negate the second purpose of this assignment. Students should study the sample solutions carefully and use them as guidance in the pursuit of “the solution” to their...

Words: 657 - Pages: 3