Table of Contents
NCERT Solutions for Class 12 Computer Science (C++) – Implementation of OOP Concepts in C++
TOPIC-1 Classes
Short Answer Type Questions-I [2 marks each]
Question 1:
Observe the following C++ code and answer the question (i) and (ii): [Delhi, 2015]
class Traveller { long PNR; char TName [20]; public : Traveller ( ) //Function 1 {cout<<"Ready"<<endl;} void Book (long P, char N [ ]) //Function 2 {PNR = P, strcpy (TName, N);} void print () //Function 3 {cout<<PNR << TName <<endl;} ~Traveller ( ) //Function 4 {cout<<"Booking cancelled!"<<endl; } ;
(i) Fill in the blank statements in Line 1 and Line 2 to execute Function 2 and Function 3 respectively in the following code: void main ( )
{
Traveller T;
___________ //Line 1
___________ //Line 2
}//Stops here
Answer:
T. Book (1234567, “Ravi”);
//Line 1
T. Print ();
//Line 2
(1/2 Mark for writing each correct Function)
[ICBSE Marking Scheme 2015]
(ii) Which function will be executed at }//Stops here ? What is this function referred as ?
Function 4
OR
~ Traveller ( )
It is a destructor function.
(1/2 Mark for writing Function 4 or- Traveller ())
(1/2 Mark for referring Destructor)
[CBSE Marking Scheme 2015]
Question 2:
Write the definition of a class PIC in C++ with following description : [Delhi, 2015]
Private Members
— Pno // Data member for Picture Number (an integer)
— Category // Data member for picture category (a string)
— Location // Data member for Exhibition Location (a string)
— FixLocation // A member function to assign // Exhibition Location as per category // as
Category | Location |
Classic | Amina |
Modern | Jim Plaq |
Antique | Ustad Khan |
Public Members
shown in the following table
— Enter ( ) // A function to allow user to enter values
// Pno, category and call FixLocation () function
— SeeAll ( ) // A function to display all the data members.
Answer:
class PIC { int Pno; char Category [20] ; char Location [20]; void FixLocation ( ); public : void Enter ( ) ; void SeeAll ( ); }; void PIC : FixLocation ( ) { if (strucmpi (category, "Classic”) = = 0) strcpy (Location, "Amina") ; else if (strcmpi (category,'' / "Modern") = = 0) strcpy (Location, "Jim Plaq") ; else if strcmpi (category, "Antique") = = 0) strcpy (Location, "Ustad khan"); void PIC : : Enter ( ) { cin>>Pno; gets (Category) ; FixLocation ( ); } void PIC : SeeAll ( ) { cout<<Pho<<Category<<Location<<endl; }
(1/2 Mark for correct syntax for class header)
(1/2 Mark for correct declaration of data members)
(1 Mark for correct definition of FixLocation ( ))
(1 Mark for correct definition of Enter ()
with proper invocation of FixLocation () function)
(1 Mark for correct definition of See All( ))
NOTE:
• Deduct % Mark if FixLocation ( ) is not invoked properly inside Enter ( ) function
• No marks to be deducted for defining Member Functions inside the class
• strcmp () strcmpi () acceptable [CBSE Marking Scheme 2015]
Question 3:
What is the difference between the members in private visibility mode and the members in protected visibility mode inside a class ? Also, give a suitable C++ code to illustrate both. [O.D, 2012]
Answer:
Private:
This type of member can only be accessed by code in the same class. [1]
Protected:
This type of member can only be accessed by code in the same class, or in a derived class. [1]
//C++ code : class Me
{
public :
int a, b;
protected :
int c, d; //protected Member
private :
int e, f; //Private Member
}
Short Answer Type Questions-II [3 marks each]
Question 1:
Observe the following C++ code and answer the questions (i) and (ii). Assume all necessary files are included. [O.D, 2016]
class BOOK { long Code; char Title[20]; float Price; Public: BOOK ( ) //Member Function 1 { cout < <"Bought"< < endl; Code=10;strcpy(Title,"NoTitle") ;Price=100; } BOOK(int C, char T[], float P) //Member Function 2 { Code=C; strcpy(Title,T); Price=P; } void Update(float P) //Member Function 3 { Price+=P; } void Display ( ) //Member Function 4 { cout<<Code<<":"<<Title<<":"<<Pr ice<<endl; } -BOOK() //Member Function 5 { cout<<"Book Discarded!"<<endl; } } ; void main() //Line 1 { //Line 2 BOOK B, C(101,"Truth",350); //Line 3 for (int I=0;I<4;I++) //Line 4 { //Line 5 B.Update(50);C.Update(20); //Line 6 B.Display 0 ;C.Display() ; //Line 7 } //Line 8 } //Line 9
(i) Which specific concept of object oriented programming out of the following is illustrated by Member Function 1 and Member Function 2 combined together ?
> Data Encapsulation
> Polymorphism
> Inheritance
> Data Hiding
(ii) How many times the message “Book Discarded!” will be displayed after executing the above C+ + code ? Out of Line 1 to Line 9, which line is responsible to display the message “Book Discarded!”?
Answer:
(i) Polymorphism
(1 Mark for mentioning the correct concept name)
(ii) 2 times
Line 9.
(1/2 Mark for writing correct number of times)
OR
(1/2 Mark for writing – “No execution due to wrong syntax in Line 3”)
OR
Any other equivalent answer conveying similar meaning
(1/2 Mark for writing correct line number)
[CBSE Marking Scheme 2016]
Question 2:
Write the definition of a class CITY in C + + with following description : [O.D, 2016]
Private Members
- CCode //Data member for City Code (an integer) - CName //Data member for City Name (a string) - Pop //Data member for Population (a long int) - KM //Data member for Area Coverage (a float) - Density //Data member for Population Density (a float) - DenCalO //A member function to calculate............... //Density as Pop/KM Public Members - Record 0 //A function to allow user to enter values of //Acode, Name, pop, KM and call DenCalO function - view //A function to display all the data members //also display a message "Highly Populated City" //if the Density is more than 10000
Answer:
Class City { int Ccode; Char CName [2 0] ; long int Pop; float KM; float Density; void Dencal (); Public : void Record(); void View(); }; void CITY :: Record ( ) { cin>>ccode; gets(C Name); cin>>pop; cin»KM; Dencal () ; } void CITY :: view() { Cout < < code < < CName <<Pop<<KM<< Density; if (Density>10000) cout<<"Highly populated city"; } void CITY :: Dencal() { Density=Pop/KM; }
Question 3:
Write the definition of a class METROPOLIS in C+ + with following description : [Delhi, 2016]
Private Members - MCode //Data member for Code (an integer) - MName //Data member for Name (a string) - MPop //Data member for Population (a long int) - Area //Data member for Area Coverage (a float) - PopDens //Data member for Population Density (a float) - CaldenO //A member function to calculate......... //Density as PopDens/Area Public Members - Ender () //A function to allow user to enter values of //MCode, MName, MPop, Area and call claDen () //function - viewall //A function to display all the data members //also display a message "Highly Populated Area" //if the Density is more than 12000
Answer:
class METROPOLIS { int MCode; char MName[2 0] ; long int MPop; float Area; float PopDens; void CalDen() public: Void Enter(); void veiw ALL(); } ; void METROPOLIS::Enter() { cin>>Mcode; gets(MName); Cin>>Mpop; Cin>>Area; CalDen(); } void METROPOLIS::viewALL ( ) { cout < <Mcode< <Mname< <Area< < "Popens", if (Pop Dens > 12000) cont<<"Highly Populated Area"; } void METROPOLIS::call Den() { PopDens =Mpop/Area } [3]
Question 4:
Answer the questions (i) to (iv) based on the following: [Delhi, 2016]
class PRODUCT { int Code; char Item[20]; protected: float Qty; public: PRODUCT(); void Getln(); void show(); { int WCode; Protected : char Manager[20]; public: WHOLE SALER(); void Enter(); void Display(); } class SHOWROOM : public PRODUCT, private WHOLE SALER { Char Name [20], public : SHOWROOM(); void Input(); void View(); } ;
(i) Which type of Inheritance out of the following is illustrated in the above example ?
– Single Level Inheritance
– Multi Level Inheritance
– Multiple Inheritance
(ii) Write the names of all the data members, which are directly accessible from the member functions of class SHOWROOM.
(iii) Write the names of all the member functions, which are directly accessible by an object of class SHOWROOM.
(iv) What will be the order of execution of the constructors, when an object of class SHOWROOM is declared ?
Answer:
(i) Multiple (ii) Name, City, Manager, Qty (iii) Input (), View (), Getln (), Show () (iv) PRODUCT (), WHOLESALER () , SHOWROOM ()
[CBSE Marking Scheme 2016]
Question 5:
Write the definition of a function Fixpay (float Pay[], int N) in C+ +, which should modify each element of the array Salary pay N elements, as per the following rules : [O.D, 2016]
Existing Pay Value | Required Modification in Value |
If less than 1,00,000 | Add 35% in the existing value |
If >=1,00,000 and <20,000 | Add 30% in the existing value |
If >=2,00,000 | Add 20% in the existing value |
Answer:
Void Fixpay (float pay[],int N) { for(int i=0; i<N; i++) { if(pay[i] < 100000) pay[i]+ = pay[i]*0.35; else if (pay[i] < 200000) pay[i]+ = pay[i]*0.30; else pay[i]+ = pay[i]*0.20; } }
Long Answer Type Questions [4 marks each]
Question 1:
Define a class Candidate in C++ with the following specification : [Delhi, 2015]
Private Mumbers:
A data members Rno (Registration Number) type long
A data member Cname of type string
A data members Agg_marks (Aggregate Marks) of type float
A data members Grade of type char
A member function setGrade() to find the grade as per the aggregate marks obtained by the student. Equivalent aggregate marks range and the respective grade as shown below.
Aggregate Marks Grade
> = 80 A
Less than 80 and > = 65 B
Less than 65 and > = 50 C
Less than 50 D
Public members:
A constructor to assign default values to data members:
Rno = 0, Cname “N.A”, Age_marks = 0.0
A function Getdata ( ) to allow users to enter values for Rno. Cname, Agg_marks and call function setGrade () to find the grade.
A function dispResult () to allow user to view the content of all the data members.
Answer:
class Candidate { long Rno; char Cname [20]; float Agg_marks; char Grade; void setGrade () { if (Agg_marks>= 80) Grade = 'A'; else if (Agg_marks<80 && Agg_ marks>=65) Grade = 'B' ; else if (Agg_marks<65 && Agg_ marks>=50) Grade = 'C'; else Grade = 'D' ; } public; Candidate ( ) { Rno=0; Strcpy (Cname, ''N.A.''); Agg_marks=0.0; } void Getdata () { cout<<''Registration No''; cin>>Rno; cout<<"Name''; cin>>Cname; cout<<Aggregate Marks''; cin>>Agg_marks; set Grade (); } void dispResult () { cout<<"Registration No''<<Rno; cout<<"Name''<<Cname; cout<<"Aggregate Marks''<<Agg_ marks; }
(1/2 mark for correct syntax for class header]
(1/2 marks for correct declaration of data members]
(1/2 mark for correct definition of the constructor Candidate ()]
[1 mark for correct definition of setGrade ()]
[1 mark for correct definition of Getdata of Getdata () with proper invocation of setGrade ()]
(1/2 mark for correct definition of dispresult]
Question 2:
Define a class Customer with the following specifications. [CBSE SQP 2015]
Private Members:
Customer_no integer
Customerjname char (20)
Qty integer
Price, TotalPrice, Discount, Netprice float
Member Functions:
Public members:
- A constructer to assign initial values of Customer_no as 111, Customer_name as “Leena”, Quantity as 0 and Price, Discount and Netprice as 0.
- Input() – to read data members (Customer_ no, Customer_name, Quantity and Price) call Caldiscount().
- Caldiscount ( ) – To calculate Discount according to TotalPrice and NetPrice
TotalPrice = Price*Qty
TotalPrice > =50000 – Discount 25% of TotalPrice TotalPrice >=25000 and TotalPrice <50000 – Discount 15% of TotalPrice TotalPrice <25000 – Discount 10% of TotalPrice Netprice = TotalPrice-Discount Show() – to display Customer details.
Answer:
class Customer { int Customer_no; char Customer_name; int Qty; float Price, TotalPrice, Discount, Netprice; public: Customer ( ) [1] { Customer_no = 111; strcpy( Customer_name, "Leena"); Qty=0 ; Price =0, Discount=0, Netprice=0; } void Input () [1] { cin>>Custome r_no; gets( Customer_name); cin>>Qty>>TotalPrice; Caldiscount(); } void Caldiscount() [1] { TotalPrice = Price*Qty; if ( TotalPrice >= 50000) Discount = 0.25 * TotalPrice; else if (TotalPrice >= 2 5000) Discount = 0.15 * TotalPrice; else Discount = 0.10 * TotalPrice; Netprice = TotalPrice - Discount; } void Show ( ) [1] { cout<<Customer_no<<" name <<" "<<Qty<" "<<TotalPrice <<" "<<Netprice; } };
Question 3:
Define a class CONTEST folowing description:
Private Data Members
Eventno integer
Description char(30)
Score integer
Qualified char
Public Member functions
• A constructor to assign initial values Evento as 11, Description’s “School level”, Score as 100, Qualified as ‘N’
• Input()-To take the input for Eventno, Description and Score.
• Award (int cutoffscore) – To assign Qualified as ‘Y’, If score is more than the cutoffscore that is passed as argument to the function, else assign Qualified as ‘N’.
• Displaydata()-to display all the data members.
Answer:
class CONTEST { private : int Eventno; char ‘Description [30]; public : Contest () ; void Input () ; void Award (int cutoffscore); [1] void Display (); }; Contest : : contest() { Evento =11 ; Description = "school level" ; Score = 100; Qualified = 'N' ; } [1] void Contest : : Input ( ) { cin >> Eventno; gets (Description); cin >> Score ; } [1] void CONTEST : : Award (in cut of score) { int K = cutoffscore ; (Score > K) Qualified = 'Y' ; else Qualified = 'N' ; } void CONTEST () { cout << Event No : << Eventno << endl ; cout << Description : << Description << endl; cout << Score : << Score << Endl cout << Qualified : << Qualified << endl; } [1]
Question 4:
Consider the following class state:
class State { protected : int tp; //no. of tourist places public : State() { tp = 0 ; } void inctp ( ) { tp++ ; } int gettp ( ) { return tp; } };
Write a code in C+ + to publically derive another
class ‘District’ with the following additional members derived in the Public visibility mode.
Data Members
distname – char (50)
population – long
Member functions:
• dinput ( ) – To enter distname and population.
• doutput ( ) – To display distname and population on screen.
Answer:
class District ; public state { [1] private : char *distname [50]; long population; pubilc : [1] void dinput () [1] { gets (distname); cin ... population ; [1] } void doutput () { puts (distname) ; cout >> population ; [1] } }
Question 5:
Define a class CABS in C++ with the following specification:
Data Members
• CNo – to store Cab No
• Type – to store a character ‘A’, ‘B’ or ‘C’ as City Type
• PKM – to store Kilo Meter charges
• Dist – to store Distance travelled (in KM)
Member Functions
• A constructor function to initialize Type as ‘A’ and CNo as ‘1111’
• A function ChargesQ to assign PKM as per
the following table:
Type | PerKM |
A | 25 |
B | 20 |
C | 15 |
• A function Register() to allow administrator to enter the values for CNo and Type. Also, this function should call Charges() to assign PKM Charges.
• A function ShowCab() to allow user to enter the value of Distance and display CNo, Type, PKM, PKM “‘Distance (as Amount) on screen [Delhi, 2014]
Answer:
class CABS { int CNo; char Type; int PKM; float Dist; CABS { Type='A'; CNo=llll; [1] } void Charges() { if (Type=='A') PKM=25; if(Type=='B') PKM=20; if(Type=='C') PKM=15; PKM= 0; } [1] void Register ( ) { cin>>CNo>>Type; PKM=Charges () ; [1] } void ShowCab() { cin>>Dist; cout<<CNo<<Type<<PKM<<PKM*Dist; } }; [1]
Question 6:
Define a class Tourist in C + + with the following specification:
Data Members
• CNo – to store Cab No
• CType – to store a character ‘A’, ‘B’, or ‘C’ as City Type
• PerKM – to store per Kilo Meter charges
• Distance – to store Distance travelled (in KM) Member Functions
• A constructor function to initialize CType as ‘A’ and CNo as ‘0000’
• A function CityCharges() to assign PerKM as per the following table:
CType | PerKM |
A | 20 |
B | 18 |
C | 15 |
• A function RegisterCab() to allow administrator to enter the values for CNo and CType. Also, this function should call CityCharges() to assign PerKM charges.
• A function Display() to allow user to enter the value of Distance and display CNo, CType, PerKM, PerKM*Distance (as Amount) on screen. [O.D, 2014]
Answer:
Class Tourist { int CNo; char CType; int PerKM; float Distance; Tourist() { CType='A'; CNo=0000; } void CityCharges () [1] { if(CType=='A') PerKm=20; if(CType=='B') PerKM=18; if(CType=='C') PerKM=15; } [1] void RegisterCab() { cin>>CNo>>CType; CityCharges(); } void Display () [1] { cin>>Distance; cout<<CNo<<CType<<PerKM<< PerKM*Distance; } [1]
Question 7:
Define a class Seminar with the following specification:
private members
Seminarld long
Topic string of 20 characters
VenueLocation string of 20 characters
Fee float
CalcFee() function to calculate Fee depending on VenueLocation
VenueLocation | Fee |
Outdoor | 5000 |
Indoor Non-AC | 6500 |
Indoor AC | 7500 |
Public members
Register() function to accept values for SeminarlD, Topic, VenueLocation and call CalcFee() to calculate Fee
ViewSeminar() function to display all the data members on the screen [CBSE Comptt., 2013]
Answer:
class Seminar { private: long Seminarld; char Topic [20] ; char VenueLocation[20]; float Fee; void CalcFeeO [1] { if (strcmp (VenueLocation, ''Outdoor'')==0) Fee=5000; else {if (strcmp (VenueLocation, ''Indoor Non-AC" ) = = 0) Fee=6500; else {if (strcmp (VenueLocation, ''Indoor AC'')==0) Fee = 7500; [1] } public: void Register () { cin>>seminarld; gets (Topic) ; gets (VenueLocation); cin>>Fee; CalcFee () ; } [1] Void ViewSeminar () { cout<<SeminarId; puts (Topic); puts (VenueLocation); cout<<Fee; } }; [1]
Question 8:
Define a class Bus in C++ with the following specifications:
Data Members
• Busno—to store Bus No
• From—to store Place name of origin
• To—to store Place name of destination
• Type—to store Bus Type such as ‘O’ for ordinary
• Distance—to store the Distance in Kilometers
• Fare—to store the Bus Fare
Member Functions
• A constructor function to initialize Type as ‘O’ and Freight as 500
• A function CalcFare( ) to calculate Fare as per the following criteria
Type Fare
‘O’ 15*Distance
‘E’ 20*Distance
‘L’ 24*Distance
• A function Allocate() to allow user to enter values for BusNo, From, To, Type and Distance. [O.D, 2013]
Answer:
class Bus { int Busno; char From [20]; charTo[20]; char Type; float Distance; float Fare, ; [1] BUS ( ) { Type='O'; Fare=500; } void CalcFare( ) [1] { if(Type=='O') Fare = 15*Distance; if (Type=='E') Fare = 20* Distance; if(Type=='L') Fare = 24*Distance; void Allocate( ) [1] { cout<<''Enter Bus Number"; cin>>Busno; cout<<''Enter Source:"; gets(From); cout<<''Enter Destination"; gets(To); cout<<''Enter Type:"; cin>>Type; cout<<''Enter Distance (in kms)"; cin>>Distance; } }; [1]
Question 9:
Define a class Tourist in C + + with the following specifications:
Data Members
• Carno—to store Bus No
• Origin—to store Place name of origin
• Destination—to store Place name
• Type—to store Car Type such as ‘E’ for Economy
• Distance—-to store the Distance in Kilometers
• Charge—to store the Car Fare
Member Functions
• A constructor function to initialize Type as ‘E’ and Freight as 250
• A function CalcCharges () to calculate Fare as per the following criteria
Type Fare
‘E’ 16* Distance
‘K’ 22* Distance
T’ 30*Distance
• A function Enter( ) to allow user to enter values for CarNo, Origin, Destination, Type and Distance. Also, this function should call CalcCharges () to calculate fare.
• A function Show() to display contents of all data members on the screen. [Delhi, 2013]
Answer:
class Tourist { int Carno; char Origin[20]; char Destination[20]; char Type; float Distance; float Charges; Tourist ( ) [1] { Type='E'; int charges=250; } void CalcCharges( ) { if(Types=='E') Charges = 16*Distance; if(Type=='A') Charges = 22‘Distance; if(Type=='L') Charges = 30*Distance; } void Enter( ) { cout<<''Enter Car Number"; cin>>Carno; cout<<''Enter Source:"; gets(Origin); cout<<''Enter Destination"; gets(Destination); cout<<''Enter Type:"; cin>>Type; cout<<''Enter Distance (in kms) " ; [1] cin>>Distance; CalcCharges( ); } void Show( ) { cout<< "Car Number:"<<Carno; cout<< "Origin:"; puts(Origin); cout<< "Destination:"; puts(Destination); cout<<"Fare:"<<Charges; } }; [1]
Question 10:
Define a class Hand set in C++ with the following description : Private members :
Make—of type string
Model—of type string
Price—of type long int
Rating—of type char
Public members:
Function Read_Data to read an object of Handset type.
Function Display( ) to display the details of an object of type Handset type.
Function RetPrice() to return the value of Price of an object of Handset type. [CBSE SQP, 2013]
Answer:
class Handset { private: char Make[20] ; char Model[20] ; long int Price; char Rating; [1] public : void Read_Data( ) { gets(Make); gets(Model); cin>>Price; [1] cin>>Rating; } void Display() { puts (Make); [1] puts(Model) ; cout<<Price; cout<<Rating; } long int RetPrice( ) { return(Price); } }; [1]
Question 11:
Find the output of the following program :
#include<iostream.h> class METRO { int Mno, TripNo, PassengerCount; public: METRO(int Tmno=l) { Mno=Tmno; TripNo=0; PassengerCount=0; } void Trip(int PC=20) { TripNo++; PassengerCount+=PC; } void StatusShow( ) { c o u t < < M n o < < " : " < < T r i p N o < < " : " < < P a s s e n g e r C o u n t < < e n d l ; } ; void main( ) { METRO M(5),T; M.Trip( ) ; T.Trip(50) ; M.StatusShow( ) ; M.Trip(30) ; T.StatusShow( ); M.StatusShow( ); } [O.D, 2012]
Answer:
5:1:20
1:1:50
5:2:50 [4]
Question 12:
Define a Class RESTRA in C++ with following description:
Private members
• Food Code of type int
• Food of type string
• FType of type String
• Sticker of type String
• A Member function GetSticker( ) to assign the following values for Food Sticker as per the given FType:
FType Sticker
Vegetarian GREEN
Contains egg YELLOW
Non-Vegetarian RED
Public Members
• A function GetFood() to allow user to enter values for FoodCode, Food, FType and call function GetSticker() to assign Sticker.
• A function ShowFood( ) to allow user to view the content of all the data members. [O.D, 2012]
Answer:
class RESTRA { char FoodCode; charFood[20] ,FType [20] ,Stick er[20]; void GetSticker() { if (strcmp (FType, ' 'Vegetari an")==0) { strcpy(Sticker,"GREEN"); } [ ] if (strcmp(FType,''ContainsEgg")==0) { strcpy(Sticker, "YELLOW"); } if (strcmp(FType,''Non-Vegetarian") ==0) strcpy(Sticker,''RED"); } public: [1] void GetFood() { cout<<"Enter FoodCode, Food, Food Type"; cin>>FoodCode; gets(Food); gets(FType); GetSticker( ); } [1] void ShowFood( ) { cout<<''Enter Food Code, Food, FoodType, Sticker:"; cout < < FoodCode; puts(Food); puts(FType); puts(Sticker); > , }; [1]
Question 13:
Find the output of the following program :
#include<iostream.h> class TRAIN { int Tno, TripNo, PersonCount, T, N; public: Train(int Tmno=l) { Tno=Tmno; TripNo=0; PersonCount = 0; } void Trip (int TC =100) {TripNo++; PersonCount =TC;} void show() {cout<<Tno<<'' : ''<<TripNo<<'' : "<<PersonCoun<<endl;} } ; void main( ) { Train T(10), N; N.Trip(); T.show(); N.Trip(70) ; N.Trip(4 0) ; N.show( ); T.show( ); } [Delhi, 2012]
Answer:
10:0:0
1:2:140
10:1:70 [4]
Question 14:
Define a class Candidate in C++ with the
following description:
Private members
• A data member RNo(Registration Number) of type long
• A data member Name of type String
• A data member Score of type float
• A data member Remarks of type String
• A member function AssignRem() to assign the remarks as per the score obtained by the candidate.
• Scor6 range and the respective remarks are shown as follow:
Score Remarks
>=50 Selected
<50 Not Selected
Public members
• A function ENTERQ to allow user to enter values for RNo, Names, Score and call function AssignRem() to assign the remarks.
• A function display() to allow user to view the content of all data members. [Delhi, 2012]
Answer:
class Candidate { long RNo; char Name[40]; float Score; [1] char Remarks[20] void AssignRem() if (Score>=50) [1] strcpy(Remarks, "Selected"); else strcpy(Remarks,''Not Selected"); } public: void Enter() { [1] cout<<''Enter the values for RNo, Name, Score"; cin>>RNo; gets(Name); cin>>Score; AssignRem( ); [1] } void Display( ) { cout<<RNo<<Score; puts(Name); puts(Remarks); } }; [1]
Question 15:
Define a class Applicant in C++ with the following description:
Private members
• A data member ANo(Admission Number) of type long
• A data member Name of type String
• data member Agg(Aggregate Marks) of type float
• A data member Grade of type char
• A member function GradeMe() to assign the grades as per the aggregate obtained by the candidate.
• Score range and the respective remarks are shown as follow:
Aggregate Grade
>=80 A
less than 80 and > = 65 B
less than 65 and > = 50 C
less than 50 D
Public members
• A function ENTER( ) to allow user to enter values for ANo, Names, Aggregate and call function GradeMe () to assign grade.
• A function RESULT( ) to allow user to view the content of all data members. [O.D, 2012]
Answer:
class Applicant { long ANo; char Name[40]; float Agg; char Grade; void GradeMe ( ) [1] { if (Agg>80) Grade='A'; if (Agg<80 && Agg>=65) Grade='B'; if (Agg<65 && Agg>=50) Grade='C'; if(Agg<50) Grade='D'; } public: void Enter ( ) { cout<<''Enter the values for Ano, Name, Agg" ; cin>>ANo; gets(Name); cin>>Agg; [1] GradeMe( ); } void Result( ) { cout<<ANo<<Agg; puts(Name); puts(Grade); } }; [1]
Question 16:
Define a class ITEM in C++ with the following description:
Private Members
• Code of type integer (Item Code)
• Iname of type string (Item Name)
• Price of type float (Price of each item)
• Qty of type integer (Quantity of item in stock)
• Offer of type float (Offer percentage on the item)
• A member function GetOffer( ) to calculate Offer percentage as per the following rule :
If Qty < = 50 Offer is 0
If 50 < Qty < = 100 Offer is 5
If Qty >100 Offer is 10
Public Members
• A function GetStock() to allow user to enter values for Code, Iname, Price, Qty and call function GetOffer() to calculate the offer.
• A function ShowItem( ) to allow user to view the content of all the data members.
Answer:
class Item { int Code; char Iname [20]; float Price; int Qty; float Offer; void GetOffer( ) ; public: void GetStock () { cin>>Code; gets (Iname) ; // OR cin. getline (Iname, 80); Or cin>>Iname; cin>>Price>>Qty; GetOfferO ; } void Showltem () { cout<<Code<<Iname<<Price<<Qty<<Offer; }; void Item : GetOffer () { if (Qty < =50) Offer = 0; else if (Qty <= 100) Offer = 5; //OR Offer = 0.05; else Offer = 10; //OR Offer = 0.1; }
(1/2 Mark for correct syntax for class header)
(1/2 Mark for correct declaration of data members) (1 Mark for correct definition of Get OfferQ)
(1 Mark for correct definition of Get Stock () with proper invocation of Get Offer () function)
(1 Mark for correct definition of ShowltemO)
Note : Deduct 1/2 Mark if Get Offer () is not invoked properly inside Stock Ofunction.
Question 17:
Define a class Stock in C++ with following description;
Private Memebrs
• ICode of type integer (Item Code)
• Item of type string (Item Name)
• Price of type float (Price of each item)
• Qty of type integer (Quantity in stock)
• Discount of type float (Discount percentage on the item)
• A member function FindDisc() to calculate discount as per the following rule :
If Qty< =50 Discount is 0
If 50<Qty,=100 Discountis 5
If Qty >100 Discount is 10
Public Members
• A function buy () to allow use to entervalue for ICode, Item, Price, Qty and call function Find Disc () to calculate the discount.
• A function Show All() to allow user to view the content of all the data members.
Answer:
class Stock { int ICode, Qty ; char Item[20] ; float Price, Discount; void FindDisc () ; public : void Buy () ; void ShowAll () ; }; void Stock : : Buy ( ) { cin>>ICode ; gets (Item) ; cin >> Price ; cin >> Qty ; Find Disc () ; } void Stock : : FindDisc () { If (Qty < = 50) Discount = 0 ; else if (Qty < = 100) Discount =5; // = 0.05 ; else Discount = 10 ; // =0.1; } void Stock : : ShowAll () { c o u t < < I C o d e < < ' \ t ' < < l t e m < < 1 \ t1<<Price<<'\t' <<Qty<<'\ t1<<Discount<<endl ; }
(1/2 Mark for correct syntax for class header)
(1/2Mark for correct declaration of data members)
(1 Mark for correct definition of FindDiscO)
(1 Mark for correct definition of Buy() with proper invocation of Find Disc() function)
(1 Mark for correct definition of Show All())
Note : Deduct 1/2 Mark if Find Disc() is not invoked properly inside Buy() function.
TOPIC-2 Objects
Short Answer Type Questions-1 [2 marks each]
Question 1:
Answer the questions (i) and (ii) after going through the following class :
class Hospital { int Pno, Dno; class Hospital public : Hospital (int PN); //Function 1 Hospital (); //Function 2 Hospital (Hospital &H); //Function 3 void In (); //Function 4 void Disp (); //Function 5 } ; void main() { Hospital H(20); //Statement 1 }
(i) Which of the functions out of Function 1, 2, 3, 4 or 5 will get executed when the Statement 1 is executed in the above code?
(ii) Write a Statement to declare a new object G
with reference to already existing object H using Function 3. [O.D, 2014]
Answer:
(i) Function 1 will get executed. [1]
(ii) Hospital G(H); [1]
Question 2:
Answer the questions (i) and (ii) after going through the following class :
class Health { int PId, Did; public: Health (int PPID); //Function 1 Health (); //Function 2 Health (Health &H); //Function 3 void Entry (); //Function 4 void Display (); //Function 5 }; void main ( ) { Health H(20); //Statement 1 }
(i) Which of the Function out of Function 1, 2, 3, 4 or 5 will get executed when the Statement 1 is executed in the above code ?
(ii) Write a statement to declare a new object G
with reference to already existing object H using Function 3. [Delhi, 2014]
Answer:
(i) Function 1 will get executed. [1]
(ii) Hospital G (H); [1]
Question 3:
What is the relationship between a class and an object? Illustrate with a suitable example. [CBSE Comptt., 2013]
Answer:
A class is a collection of objects. Each object represents the behaviour and functions, which the class members can performs. In other words, an object is an instance of a class. [1]
For Example:
A Class Box will have characteristics as length, breadth and height:
class Box { int length, breadth, height; void Display (int length, int breadth, int height) {cout<<length<<breadth<<height;} }; void main() {Box a=new Box(); a. Display(10,20,30); // a is the object of class Box [1] }
NCERT Solutions for Class 12 Computer Science (C++) – Object Oriented Programming in C++
TOPIC – 1
Object Oriented Programming : Introduction
Short Answer Type Questions-I [2 marks each]
Question 1:
Differentiate between data abstraction and data hiding. [Delhi, 2015]
Answer:
Data hiding can be defined as the mechanism of hiding the data of a class from the outside world. This is done to protect the data from any accidental or intentional access. Data hiding is achieved by making the members of the class private.
Data abstraction refers to, providing only essential information to’ the outside world and hiding their background details.
Members defined with a public label are accessible to all parts of the program. The data abstraction view of a type is defined by its public members.
https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7398766921532682&output=html&h=280&slotname=8094000682&adk=2916952469&adf=4000517792&pi=t.ma~as.8094000682&w=750&fwrn=4&fwrnh=100&lmt=1670952986&rafmt=1&format=750×280&url=https%3A%2F%2Fwww.cbsetuts.com%2Fncert-solutions-class-12-computer-science-c-object-oriented-programming-c%2F&fwr=0&rpe=1&resp_fmts=3&wgl=1&uach=WyJXaW5kb3dzIiwiNi4wLjAiLCJ4ODYiLCIiLCIxMDguMC41MzU5LjEyNSIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIk5vdD9BX0JyYW5kIiwiOC4wLjAuMCJdLFsiQ2hyb21pdW0iLCIxMDguMC41MzU5LjEyNSJdLFsiR29vZ2xlIENocm9tZSIsIjEwOC4wLjUzNTkuMTI1Il1dLGZhbHNlXQ..&dt=1672668060665&bpp=1&bdt=1913&idt=167&shv=r20221207&mjsv=m202212060101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Dabbbd049660c1ef5-2201b28402d90024%3AT%3D1671719836%3ART%3D1671719836%3AS%3DALNI_MazhTIzYkzGHXl260j5g4NFTSeuqQ&gpic=UID%3D00000b960889abfa%3AT%3D1671719836%3ART%3D1672666984%3AS%3DALNI_MZitKfGKipH7BopsZPzcTHmvXnt4Q&prev_fmts=0x0&nras=1&correlator=7214502721993&frm=20&pv=1&ga_vid=1762681568.1671719837&ga_sid=1672668061&ga_hid=1428470902&ga_fc=1&u_tz=330&u_his=4&u_h=864&u_w=1536&u_ah=824&u_aw=1536&u_cd=24&u_sd=1.25&dmc=4&adx=190&ady=938&biw=1519&bih=754&scr_x=0&scr_y=0&eid=44759876%2C44759927%2C44759837%2C44777506%2C31071220%2C44780792&oid=2&pvsid=4316515859347442&tmod=908382715&uas=0&nvt=1&ref=https%3A%2F%2Fwww.learncbse.in%2F&eae=0&fc=1920&brdim=0%2C0%2C0%2C0%2C1536%2C0%2C1536%2C824%2C1536%2C754&vis=1&rsz=%7C%7CeEbr%7C&abl=CS&pfx=0&cms=2&fu=128&bc=31&ifi=2&uci=a!2&btvi=1&fsb=1&xpc=JwsBddRira&p=https%3A//www.cbsetuts.com&dtd=182
Question 2:
How encapsulation and abstraction are implemented in C++ language ? Explain with an example. [CBSE SQP 2015]
Answer:
Abstraction refers to the act of representing essential features without including the back-ground details or explanations.
Encapsulation is wrapping up of data and function together in a single unit.
We can say that encapsulation is way of achieving abstraction. Both these concepts are implemented in C++ in the form of a class. In a class data and function members are wrapped together. Only essential features are shown to the outside world in the form of member functions with public mode of accessibility. [1]
Example: [1]
class Rectangle { int L, B; public: void Input() { cin>>L>>B; } void Output() { Cout<<L<<B; } };
In this example:
Data and member functions are together encapsulated
Only Input ( ) and Output ( ) functions are visible outside the class which can only can be accessed outside the class using objects of the same class – Abstraction
Question 3:
Explain data hiding with an example. [CBSE Comptt., 2014]
Answer:
Data Hiding
Data Hiding is the mechanism where the details of the class are hidden from the user.
The user can perform only a restricted set of operations in the hidden member of the class For example,
In order to make the design and maintenance of a car reasonable the complexity of equipment is divided into modules with particular interfaces hiding design decisions.
General Form:
class classname { private: datatype data; public: Member functions,-' }; main() { classname objectnamel, objectname2
.........; { Example :
class Square
{ private int Num; public: void Get() { cout<<"Enter Number:"; cin>>Num; } void Display!) { cout<<"Square Is:"<<Num*Num; } }; void main() { Square Obj; Obj.Get(); Obj.Display (); [1] getch() }
Question 4:
What do you understand by data encapsulation and Data hiding ?
Also, give a suitable C++ code to illustrate both. [CBSE SQP 2013]
Answer:
Data hiding is a property of OOP by which the crucial data of an object is made hidden from the rest of the program or outside the world. [1]
Encapsulation refers to the wrapping of data and associated functions together under a unit class. [1]
// Program for hiding & Encapsulation #include <iostream.h> class Adder { // Encapsulation public : Adder (int i = 0) { total = i;} void addNum (int Number) { total + = Number; } int getTotal ( ) { return total; } private : int total ; //Data Hiding }; int main ( ) { Adder a; a . addNum (10); a . addNum (20); a . addNum (30); cout << "Total :<<a.getTotal ( ) < < endl; return 0 ; }
Question 5:
Write the output of the following C++ program code: [Delhi, 2015]
class Eval { char Level; int Point; Public : Eval () { Level = 'E' ; Point = 0; } void Sink (int L) { Level - = L; } void Float (int L) { Level + = L; Point ++; } void Show ( ) { cout<<Level<<"#"<<Point<<endl; } }; void main ( ) { Eval E; E. Sink (3) ; E. Show ( ); E. Float (7); E. Show ( ); E. Sink (2) ; E. Show ( ); }
Answer:
B#0
I#1
G#1
(1 Mark for each correct line of output)
Note:
• Deduct 1/2 Mark for not considering any or all end/(s) at proper place(s)
• Deduct 1/2 Mark for not writing any for all symbol(s) [CBSE Marking Scheme 2015]
Question 6:
Observe the following program carefully and attempt the given questions :
#include<iostream.h>
#include<cono.h>
#include<stdlib,h>
void main()
clrscr();
randomize();
char courses![ ] [10]={“M.Tech”.”MCA”, “MBA”,”B.Tech”};
int ch;
for(int i= l;i<=3;i++)
{
ch=random(i)+1;
cout<<courses[ch]<<“\t;
}
getch () ;
}
(i) Out of all the four courses stored in the variable courses, which course will never be displayed in the output and which course will always be displayed at first in the output ?
(ii) Mention the minimum and the maximum value assigned to the variable ch ? [CBSE SQP 2016]
Answer:
(i) M. Tech will never be displayed in the output.
MCA will always be displayed at first in the output.
(ii) Minimum value of ch=l
Maximum value of ch=3
(1 Mark for each correct answer)
Note:
• Deduct 1/2 Mark for writing any additional option. [CBSE Marking Scheme 2016]
Question 7:
Study the following program and select the possible output(s) from the options (i) to (iv) following it. Also, write the maximum and the minimum values that can be assigned to the variable VAL.
Note:
— Assume all required header files are already being included in the program.
— random(n) function generates an integer between 0 and n -1. [O.D, 2015]
void main () { randomize () ; int VAL; VAL = random (3) + 2; chart GUESS [ ] = "ABCDEFGHIJK" ; for (int I = 1; I < = VAL; I ++) { for (int J = VAL; J < = 7; J ++) Cout<<GUESS [J] ; cout<<endl; }
Answer:
(ii) and (iii)
Min Value of VAL = 2
Max Value of VAL. = 4
(1/2 CA Mark for writing option (ii))
(1/2 Mark for writing option (iii))
Note:
• Deduct 1/2 mark for ivriting each additional option along with both correct options:
(1/2 Mark for writing correct Minimum value of VAL)
(1/2 Mark for writing correct Maximum value of VAL) [CBSE Marking Scheme 2015]
Question 8:
Rewrite the following program after removing the syntax errors (if any). Under line each correction. [O.D, 2012]
#include <iostream.h> Class Item { long IId, Qty; public : void Purchase {cin>>IId>>Qty;} void sale () { cout<<setw (5)<< IId<<" Old :"<Qty <<endl; cout<<"New :" <<Qty<<endl; } }; void main () { Item I; Purchase (); I. Sale () ; I. Sale () }
Answer:
#include<iostream.h> #include<iomanip.h> class Item { long IId, Qty; public : void purchase() {cin>>IId>>Qty;} void sale() { cout<<setw(5)<<IId<<"Old"<<Qty<<endl; cout<< "New Qty<<endl; } }; void main( ) { Item I ; I. purchase( ); // Object missing I. sale ( ) ; I. sale( ); //; is missing } (1/4 mark for each correction)
Question 9:
Rewrite the following program after removing the syntax errors (if any). Underline each correction. [Delhi, 2012]
# include <iostream.h> class book { long Bid, Qty; public : void purchase () {cin>>BID>>Qty;} void sale ( ) { cout<<setw<<BId<<"Old:"<<Qty<<en dl; cout<<"New; "<<—Qty<<endl; } }; void main () { Book B; B. Purchase(); sale (); B. Sale () }
Answer:
#include<iomanip.h> #include<iostream.h> class Book { long Bid, Qty; public: void purchase()(cin>>Bld>>Qty;) void sale( ) { cout < < setw(5) < < Bld < < "0ld " < < Qty < < e n dl; cout<"New:"<<—Qty<<endl; } } ; void main () { Book B; B. purchase (); B. sale(); } (1/2 mark for each correction) [CBSE Marking Scheme 2012]
Question 10:
Answer the questions (i) and (ii) after going through the following class: [O. D, 2012]
class Travel { int PlaceCode; char Place [20] ; float Charges; public : Travel ( ) //Function 1 { PlaceCode = 1; strcpy (Place, "DELHI"); Charges =1000; } void TravelPlan (float C) //Function 2 { cout<<PlaceCode<< ":" <<Place<< ":" <<Charges<<endl;
} - Travel ( ) //Function 3 { cout<<"Travel Plan Cancelled"<< endl; } Travel (int PC, char P [], float C) // Function 4 { PlaceCode = PC; strcpy (Place, P); Charges = C; } } ;
(i) In Object Oriented Programming, what are Function 1 and Function 4 combinely referred to as ?
(ii) In Object Oriented Programming which concept is illustrated by Function 3? When is this function called/invoked ?
Answer:
The concept demonstrated is constructor over-loading:
(i) Function 1 and Function 4 are called overloaded Constructor of the Class Travel.
(ii) Function 3 is Destructor of Class Travel.
The destructors are called automatically
when the objects are destroyed. [2]
Short Answer Type Questions-II (3 marks each)
Question 1:
Write any four important characteristics of object Oriented Programming ? Give example of any one of the characteristics using C++. [O.D, 2016]
Answer:
Question 2:
Find the output of the following C++ program [CBSE SQP 2015]
#include<iostream.h> #include<conio.h> #include<ctype.h> class Class { int Cno,total; char section; public: Class(int no=l) { Cno=no; section='A'; total=30; } void admission(int c=20) { section++; total+=c; } void ClassShow () { cout<<Cno<<":"<<section<<":"<<total< endl; } }; void main () { Class C1 (5),C2; Cl.admission(25) Cl.ClassShow(); C2.admission() ; Cl.admission(30) C2.ClassShow(); Cl.ClassShow(); }
Answer:
5 : B : 55 [1]
1: B : 50 [1]
5 : C : 85 [1]
Question 3:
Obtain the output of the following C+ + program, which will appear on the screen after its execution.
Important Note:
• All the desired header files are already included in the code, which are required to run the code,
class Game { int Level, Score; char Type; public: Game (char GType='p') {Level=1; Score=0; Type= GType;} void Play (int GS); void Change (); void Show() { cout<<Type<<"@"<<Level<<endl; cout<<Score<<endl; } } ; void main () { Game A ('G'), B; B. Show (); A. Play (11); A. Change (); B. Play (25); A. Show (); B. Show (); } void Game: : Change() { Type=(Type== 'P')?'G' :'P'; } void Game: :Play(int GS) { Score+=GS; if(Score>=30) Level=3; else if (Score>=20) Level=2; else Level=l; } [O.D, 2014]
Answer:
P@1
0
P@1
11
P@2
25
(1/2 mark for each correct line)
Question 4:
Obtain the output of the following C+ + program, which will appear on the screen after its execution.
Important Note:
• All the desired header files are already included in the code, which are required to run the code,
class Player { int Score, Level; char Game; public: Player (char GGame='A') {Score=0; Level=1; Game =GGame;} void Start (int SC); void Next (); void Disp () { cout <<Game<<"@"<<Level <<endl; cout <<Score<<endl; } }; void main () { Player P,Q ('B'); P. Disp (); Q. Start (75); Q. Next (); P. Start (120); Q. DispO ; P.Disp (); } void Player : : Next () { Game = (Game =='A')?'B':'A' ; } void Player : : Start (int SC) { Score+=SC; If (Score>=100) Level=3; else if (Score>=50) Level=2; else Level=1; } [O.D, 2014]
Answer:
A@1 0
A@2
75
A@3
120 [3]
Question 5:
Observe the following C++ code carefully and obtain the output, which will appear on the screen after execution of it.
#include <iostream.h> class Mausam { int city, Temp, Humidity; public : Mausam (int C = 1) {City = C; Temp = 10; Humidity = 63;}; void Sun (int T) {Temp + = T;}; void Rain (int H) {Humidity +=H;}; void Checkout ( ) { cout<<City<<":"<<Temp<< "&" <<Humidity <<"%"<<endl; } } ; void main ( ) { Mausam M, N(2); M. Sun (5); M. Checkout ( ); N. Rain (10); N.Sun (2) ; N.Checkout ( ); M.Rain (15) ; M.Checkout ( ) ; } [O.D, 2013]
Answer:
Output:
1:1:15% [1]
2:2:12% [1]
3:1:15% [1]
Question 6:
Observe the following C++ code carefully and obtain the output, which will appear on the screen after execution of it.
# include <iostream.h> class Aroundus { int Place, Humidity, Temp; public: Aroundus(int p = 2) { Place = P; Humidity = 60; Temp = 20; } void Hot (int T) { Temp+=T ; }; void Humid (int H) { Humidity+=H ; }; void JustSee ( ) { cout<<Place<<":"<<Temp<<"&"<<Humidity <<"%"<<endl; } }; int main() { Aroundus A, B (5) ; A. Hot (10) ; A. JustSee ( ) ; B. Humid (15) ; B. Hot (2) ; B. JustSee ( ) ; A. Humid (5) ; A. Justsee ( ) ; [Delhi, 2013]
Answer:
Output:
2 : 30 & 60% [1]
5 : 22 & 75% [1]
2 : 30 & 65% [1]
Question 7:
Find the output of the following program : [O.D., 2012]
#include <iostream.h> class METRO { int Mno, TripNo, PassengerCount; public : METRO (int Tmno=l) { Mno=Tmno; TripNo=0; PassengerCount=0; } void Trip (int PC = 20) { TripNo++; PassengerCount+=PC;} void StatusShow () {cout<<Mno<<" : "<<TripNo<<":" <<PassengerCount<<endl;} } ; int main () { METRO M (5), T; M.Trip () ; T.Trip (50) ; M.StatusShow (); M.Trip (30) ; T.StatusShow (); M.StatusShow (); }
Answer:
Output:
5 :1: 20
1 :1 : 50
5 : 2 : 50
(1 mark for each line of output)
Question 8:
Find the output of the following program: [Delhi, 2012]
#include<iostream.h> class TRAIN { int Tno, TripNo, PersonCount; public : TRAIN (int Tmno=l) {Tno=Tno; TripNo=0; PersonCount = 0;} void Trip (int TC=100) {TripNo++; PersonCount+=TC;} void Show () {cout<<Tno<<" : "<<Trip’No<<" : "<<Person Count <<endl;} }; void main () { TRAIN T (10), N. N. Trip () ; T. Show () ; T. Trip (70) N. Trip (40) N. Show () ; T. Show () ; }
Answer:
Output:
1202 : 0:0
950 : 2 :140
1202 :1: 70
(1 mark for each line of output)
Question 9:
Write the output of the following C++ progam code:
Note : Assume all required header files are already being included in the program,
class seminar { char topic [30]; int charges; public: { strcpy(topic,"Registration"); charges=5000; } seminar(char t [ ] ) { strcpy (topic,t) charges = 5000; } seminar (intc) { strcpy(topic,"Registration with Discount") ; charges=5000-c; } void regis(char t [ ], int c) { strcpy(topic, t); charges=charges+c; } void regis(int c=2000) { charges=charges+c; } void subject(char t [ ],int c) { strcpy(topic,t); charges=charges+c; } void show ( ) { cout<<topic<<"@<<charges<<endl; } }; void main ( ) { seminar s1,s2(1000),s3("Genetic Mutation") , s4; s1.show ( ); s2.show ( ); s1.subject("ICT",2000) ; s1.show ( ); s2.regis("Cyber Crime",2500); s2.show ( ); s3.regis ( ) ; s3.show(); s4=s2; s4.show(); getch(); } [CBSE SQP, 2016]
Answer:
Registration@5000 Registration with Discount@4000 ICT@7000 Cyber Crime@6500 Genetic Mutation@7000 Cyber Crime@6500
(1/2 mark for each correct output)
Note:
Deduct 1/2 Mark for not considering any “@” symbol [CBSE Marking Scheme, 2016]
Question 10:
Find and write the output of the following C+ + program code:
Note : Assume all required header files are already being included in the program,
class product { int PID' float price; int Qty; public: Product ( ) {PID=100;Price=20;Qty=100;} void Add(int I, float p) { ID=I ; Price=P; } void Alter(int Change,int TQ) { Price+=Change; Qty+=TQ; } void Display ( ) { cout<<"PID:"<<PID<<endl; cout<<Qty<<"@"<<Price<<endl; } }; void main ( ) { Product P,Q,R; P. Add(104,50); Q. Add(201,30) ; R. Alter(-10,25) ; P. Display(); Q. Display(); R. Display(); }
Answer:
PID: 100 104@150 PID:29 201 @130 PID:25 100@10
(1/2 mark for each correct line of output)
Note:
• Deduct only 1/2 Mark for not writing any or all.
• Deduct 1/2 Mark for not considering any or all
TOPIC-2
Function Overloading
Short Answer Type Questions-1 [2 marks each]
Question 1:
Answer the questions (i) and (ii) after going through the following class :
class Motor { int MotorNo. Track; public : Motor ( ); //Function 1 Motor (int MN) ; //Function 2 Motor (Motor &M); //Function 3 void Allocate ( ) ///Function 4 void Move ( ); //Function 5 } ; void main ( ) { Motor M; }
(i) Out of the following, which of the option is correct for calling Function 2?
Option 1 – Motor N (M);
Option 2 – Motor P (10);
(ii) Name the feature of Object Oriented
Programming, which is illustrated by Function 1, Function 2 and Function 3 combined together. [Delhi, 2013]
Answer:
(i) Option 2 is correct for calling Function 2. [1]
(ii) Function overloading, i.e., Polymorphism. [1]
Question 2:
Answer the questions (i) and (ii) after going through the following class :
class Race { int CarNo, Track; public: Race ( ) ; //Function 1 Race (int CN) ; //Function 2 Race (Race &R); //Function 3 void Register ( ); //Function 4 void Drive ( ); //Function 5 }; void main ( ) { Race R ; : }
(i) Out of the following, which of the option is correct for calling Function 2?
Option 1 – Race T (30);
Option 2 – Race U (R);
(ii) Name the feature of Object Oriented
Programming, which is illustrated by Function 1, Function 2 and Function 3 combined together. [O.D, 2013]
Answer:
(i) Option 1 – Race T (30); is correct since the parameter to T is integer. [1]
(ii) When Functions – Function 1, Function 2 and Function 3 are combined together, it is referred as constructor overloading, i.e., Polymorphism. [1]
Question 3:
What is function overloading ? Write an example using C++ to illustrate the concept of function overloading.
Answer:
Function Overloading
In C++, we can declare different functions with same name. This property is called function overloading. Function overloading implements polymorphism.
Example:
# include <iostream.h >
#include < stdlib.h>
#include < conio.h>
#define pi 3.14
class fn [1] { public: void area(int); //circle void area(int,int); //rectangle }; void fn : : area(int a) { cout <<"Area of Circle:"<<pi*a*a; } void fn::area (int a, int b) { cout <<"Area of rectangle:"<<a*b; } void main ( ) { int ch; int a, b, r; fn obj; cout<<''\nl.Area of Circle\ n2.Area of Rectangle\ n3.Exit\n:"; cout<<''Enter your Choice:"; cin>>ch; switch(ch) { case 1: cin>>r; obj.area(r); break; [1] case 2: 'cin>>a>>b; obj.area(a,b); break; case 3: exit (0); } getch ( ); }
Question 4:
Write the output of the following C++ code. Also, write the name of feature of Objects Oriented Programming used in the following program jointly illustrated by the functions [I] to [IV]
include<iostream.h> void Line ( ) //Function[I] { for(int L=1;L<=80;L++) Cout<<"-"; cout<<endl; } void Line(int N) //Function[II] { for (int L=1;L<=N;L++) Cout<<"*"; cout<<endl; } void Line (char C, Int N) //Function[III] { for(int L=1;L<=N;L++) Cout<<C; cout<<endl; } Void Line (int M, int, N) //Function [IV] { for (int L = 1;L<=N;L++) cout<<M*L; cout<<endl; } void main ( ) { int A=9, B=4 C=3; char K = "#" ; Line (K, B); Line (A,C); }
Answer:
####
91827
Function Overloading
(1/2 Mark for writing each correct output)
(1 Mark for writing the feature, name correctly)
Question 5:
Answer the question (i) and (ii) after going through the following class :
class Test { int Regno, Max, Min, Score; public : Test ( ) //Function 1 { Regno =101; Max = 100; Min=40; Score=75 ; } Test (int Pregno, int Pscore) //Function 2 { Regno=Pregno;Max=100;Min=40; Score=Pscore; } ~Test() //Function 3 { cout<<"Test Over"<<endl; } void Display ( ) //Function 4 { cout<<Regno<<":"<<Max<<":"<<Min<< endl ; cout<<" [Score]"<<Score<<endl ; } } ;
(i) As per object oriented programming which concept is illustrated by function 1 and function 2 together ?
Answer:
Polymorphism
OR
Function Overloading
OR
Constructor Overloading
(1 Mark for naming the concept correctly)
(ii) What is Function 3 specially referred as ? When do you think, Function 3 will be invoked/called ?
Answer:
Destructor is invoked or called when scope of an Object gets over.
(1/2 Mark of naming Destructor correctly)
(1/2 Mark for mentioning correctly when it is invoked)
Question 6:
Answer the questions (i) and (ii) after going through the following class :
class Exam { int Rno, Maxmarks, MinMarks, marks; pubic : Exam () //Module 1 { Rno=101;MaxMarks=100;MinMarks=40; Marks =75 ; } Exam (int Prno, int Pmarks) / / Module 2 { Rno = Prno;MaxMarks = l0 0;MinMar ks=40; Marks=Pmarks; } -Exam () //Module 3 { cout<<"Exam Over" <<Endl ; } void show ( ) //module 4 { cout<<Rno<<" : "< <MaxMarks < <":"<< MinMarks <<endl; cout<<"[Marks Got]" <<Marks<<endl; } };
(i) As per Object Oriented Programming, which concept is illustrated by Module 1 and Module 2 together ?
Answer:
Polymorphism
Or
Constructor Overloading
OR
Function Overloading
(1 Mark for mentioning the correct concept)
(ii) What is Module 3 referred as ? When do you think, Module 3 will be invoked/called ?
Answer:
Destructor. It is invoked as soon as the scope of the object gets over.
(1/2 Mark for indentifying it as Destructor)
(1/2 Mark for mentioning correctly when it be called/invoked)
Question 7:
What do you understand by Function overloading or functional polymorphism? Explain with suitable example.
Answer:
Function overloading is a method of using the same function or method to work using different sets of input. It is one of the example of polymorphism, where more than one function carrying similar name behaves differently with different set of parameters passed to them,
void show () { cout<<"\n Hello World!"; } void show(char na [ ]) { cout<<"\n Hello Word! Its"<<na;