Refer to CBSE Class 12 Computer Science HOTs Programming in C++. We have provided exhaustive High Order Thinking Skills (HOTS) questions and answers for Class 12 Computer Science Programming in C++. Designed for the 2026-27 exam session, these expert-curated analytical questions help students master important concepts and stay aligned with the latest CBSE, NCERT, and KVS curriculum.
Programming in C++ Class 12 Computer Science HOTS with Solutions
Practicing Class 12 Computer Science HOTS Questions is important for scoring high in Computer Science. Use the detailed answers provided below to improve your problem-solving speed and Class 12 exam readiness.
HOTS Questions and Answers for Class 12 Computer Science Programming in C++
1 Marks Questions
Question. Observe the program segment carefully and answer the question that follows:
class item
{
int item_no;
char item_name[20];
public:
void enterDetail( );
void showDetail( );
int getItem_no( ){ return item_no;}
};
void modify(item x, int y )
{
fstream File;
File.open( "item.dat", ios::binary | ios::in | ios::out) ;
item i;
int recordsRead = 0, found = 0;
while(!found && File.read((char*) &i , sizeof (i)))
{
recordsRead++;
if(i . getItem_no( ) == y )
{
_________________________//Missing statement
File.write((char*) &x , sizeof (x));
found = 1;
}
}
if(! found)
cout<<"Record for modification does not exist" ;
File.close() ;
}
If the function modify( ) is supposed to modify a record in the file "item.dat", which item_no is y, with the values of item x passed as argument, write the appropriate statement for the missing statement using seekp( ) or seekg( ), whichever is needed, in the above code that would write the modified record at its proper place.
Answer:
Using seekp():
File.seekp(Record * sizeof(i)); // using object name
OR
File.seekp(Record * sizeof(item)); // using class name
OR
File.seekp(File.tellg() - sizeof(i));
OR
File.seekp(File.tellg() - sizeof(item));
OR
File.seekp(-sizeof(i), ios::cur);
Using seekg():
File.seekg(Record * sizeof(i));
OR
File.seekg(Record * sizeof(item));
OR
File.seekg(-sizeof(i), ios::cur);
Question. Observe the program segment carefully and answer the question that follows:
class member
{
int member_no;
char member_name[20];
public:
void enterDetail( );
void showDetail( );
int getMember_no( ){ return member_no;}
};
void update(member NEW )
{
fstream File;
File.open( "member.dat", ios::binary|ios::in|ios::out) ;
member i;
while(File .read((char*) & i , sizeof (i)))
{
if(NEW . getMember_no( ) == i . getMember_no( ))
{
_________________________//Missing statement
File.write((char*) &NEW , sizeof (NEW));
}
}
File.close() ;
}
If the function update( ) is supposed to modify the member_name field of a record in the file "member.dat" with the values of member NEW passed as argument, write the appropriate statement for the missing statement using seekp( ) or seekg( ), whichever is needed, in the above code that would write the modified record at its proper place.
Answer: Same as previous question. Just change the class name or object name. For example:
File.seekp(-sizeof(i), ios::cur);
OR
File.seekp(File.tellg() - sizeof(i));
OR
File.seekp(File.tellg() - sizeof(member));
Question. Observe the program segment carefully and answer the question that follows:
class item
{
int item_no;
char item_name[20];
public:
void enterDetails( );
void showDetail( );
int getItem_no( ){ return item_no;}
};
void modify(item x )
{
fstream File;
File.open( "item.dat", _______________ ) ; //parameter missing
item i;
while(File .read((char*) & i , sizeof (i)))
{
if(x . getItem_no( ) == i . getItem_no( ))
{
File.seekp(File.tellg( ) - sizeof(i));
File.write((char*) &x , sizeof (x));
}
else
File.write((char*) &i , sizeof (i));
}
File.close() ;
}
If the function modify( ) modifies a record in the file "item.dat" with the values of item x passed as argument, write the appropriate parameter for the missing parameter in the above code, so as to modify record at its proper place.
Answer: You have to complete the syntax of file opening.
File.open( "item.dat", ios::binary|ios::in|ios::out ) ;
Question. Observe the program segment carefully and answer the question that follows:
class member
{
int member_no;
char member_name[20];
public:
void enterDetails( );
void showDetail( );
int getMember_no( ){ return member_no;}
};
void update(member NEW )
{
fstream File;
File.open( "member.dat", ios::binary|ios::in|ios::out) ;
member i;
while(File .read((char*) & i , sizeof (i)))
{
if(NEW . getMember_no( ) == i . getMember_no( ))
{
File.seekp( _________ , ios::cur ) //Parameter Missing
File.write((char*) &NEW , sizeof (NEW));
}
}
File.close() ;
}
If the function update( ) is supposed to modify a record in the file "member.dat" with the values of member NEW passed as argument, write the appropriate parameter for the missing parameter in the above code, so as to modify record at its proper place.
Answer: File.seekp( -sizeof(i), ios::cur );
Question. Observe the program segment given below carefully, and answer the question that follows:
class Applicant
{
long AId; //Applicant’s Id
char Name[20]; //Applicant’s Name
float Score; //Applicant’s Score
public:
void Enroll();
void Disp();
void MarksScore(); //Function to change Score
long R_Aid() {return Aid;}
};
void ScoreUpdate(long Id)
{
fstream File;
File.open("APPLI.DAT",ios::binary|ios::in|ios::out);
Applicant A;
int Record=0,Found=0;
while (!Found&&File.read((char*)&A, sizeof(A)))
{
if (Id==A.R_Aid())
{
cout<<"Enter new Score…";
cin>>A.MarksScore();
_________________ //statement 1
_________________ //statement 2
Found = 1;
}
Record++;
}
if(Found==1) cout<<"Record Updated";
File.close();
}
Write the Statement1 to position the File Pointer at the beginning of the Record for which the Applicant’s Id matches with the argument passed, and Statement2 to write the updated Record at that position.
Answer:
Statement 1:
File.seekp(Record * sizeof(A)); //using object name
OR
File.seekp(Record * sizeof(Applicant)); //using class name
OR
File.seekp(File.tellg() - sizeof(A));
OR
File.seekp(File.tellg() - sizeof(Applicant));
OR
File.seekp(-sizeof(A), ios::cur);
OR
File.seekg(Record * sizeof(A));
OR
File.seekg(Record * sizeof(Applicant));
OR
File.seekg(-sizeof(A), ios::cur);
Statement 2:
File.write((char*)&A, sizeof(A));
OR
File.write((char*)&A, sizeof(Applicant));
Question. Observe the program segment carefully and answer the question that follows:
class student
{
int student_no;
char student_name[20];
int mark;
public:
void enterDetail( );
void showDetail( );
void change_mark( ); //Function to change the mark
int getStudent_no( ){ return student_no;}
};
void modify( int y )
{
fstream File;
File.open( "student.dat", ios::binary|ios::in|ios::out) ;
student i;
int recordsRead = 0, found = 0;
while(!found && File .read((char*) & i , sizeof (i)))
{
recordsRead++;
if(i . getStudent_no( ) == y )
{
i . change_mark( );
_________________________//Missing statement 1
_________________________//Missing statement 2
found = 1;
}
}
if( found == 1)
cout<<"Record modified" ;
File.close() ;
}
If the function modify( ) is supposed to change the mark of a student having student_no y in the file "student.dat", write the missing statements to modify the student record.
Answer: First we have to move the file pointer to the appropriate place (Statement 1) and then write the record on that location (Statement 2).
Missing statement 1:
File.seekp(File.tellg() - sizeof(i));
OR
File.seekp(-sizeof(i), ios::cur);
OR
File.seekp((recordsRead - 1) * sizeof(student));
Missing statement 2:
File.write((char*)&i, sizeof(i));
Question. Observe the program segment carefully and answer the question that follows:
class item
{
int item_no;
char item_name[20];
public:
void enterDetail( );
void showDetail( );
int getItem_no( ){ return item_no;}
};
void modify(item x )
{
fstream File;
File.open( "item.dat", ios::binary|ios::in|ios::out ) ;
item i;
while(File .read((char*) & i , sizeof (i)))//Statement 1
{
if(x . getItem_no( ) == i . getItem_no( ))
{
File.seekp(File.tellg( ) - sizeof(i));
File.write((char*) &x , sizeof (x));
}
}
File.close() ;
}
If the function modify( ) modifies a record in the file "item.dat" with the values of item x passed as argument, rewrite statement 1 in the above code using eof( ) , so as to modify record at its proper place.
Answer:
while(!File.eof ( )) {
File.read((char*) & i , sizeof (i));
Question. Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekp() and seekg() functions for performing the required task.
#include <fstream.h>
class Item
{
int Ino;char Item[20];
public:
//Function to search and display the content from a particular record number
void Search(int );
//Function to modify the content of a particular record number
void Modify(int);
};
void Item::Search(int RecNo)
{
fstream File;
File.open("STOCK.DAT",ios::binary| ios::in);
______________________ //Statement 1
File.read((char*)this,sizeof(Item));
cout<<Ino<<"==>"<<Item<<endl;
File.close();
}
void Item::Modify(int RecNo)
{
fstream File;
File.open("STOCK.DAT",ios::binary|ios::in|ios::out);
cout>>Ino;
cin.getline(Item,20);
______________________ //Statement 2
File.write((char*)this,sizeof(Item));
File.close();
}
Answer:
Statement 1: File.seekg(RecNo * sizeof(Item));
Statement 2: File.seekp(RecNo * sizeof(Item));
Question. Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg() and tellg() functions for performing the required task.
#include <fstream.h>
class Employee
{
int Eno;char Ename[20];
public:
//Function to count the total number of records
int Countrec();
};
int Item::Countrec()
{
fstream File;
File.open("EMP.DAT",ios::binary|ios::in);
______________________ //Statement 1- To take the file pointer to the end of file.
int Bytes =
______________________ //Statement 2-To return total number of bytes from the beginning of file to the file pointer.
int Count = Bytes / sizeof(Item);
File.close();
return Count;
}
Answer:
Statement 1: File.seekg(0, ios::end);
Statement 2: File.tellg();
Question. Observe the program segment given below carefully and fill the blanks marked as Statement 1 and Statement 2 using seekg() and tellg() functions for performing the required task.
class Library
{
long Ano;
char Title[20];
int Qty;
public:
void Enter(int);
void Display();
void Buy(int Tqty)
{
Qty+=Tqty;
}
long GetAno( ) { return Ano;}
};
void BuyBook(long BAno. Int BQty)
{
fstream File;
File.open("STOCK.DAT",ios::binary|ios::in|ios::out);
int Position=-1;
Library L;
while(Position==-1&&File.read((char*)&L, sizeof(L)))
{
If(L.GetAno()==BAno)
{
L.Buy(BQty);
Position=File.tellg()-sizeof(L);
//Line1: To place the file pointer to the required position
__________________________________;
//Line2: To write the object L on to the binary file
___________________________________;
}
If(position==-1)
cout<<"No updation done as required Ano not found";
File.close();
}
Answer:
Line 1:
File.seekp(Position);
OR
File.seekp(-sizeof(L), ios::cur);
OR
File.seekg(-sizeof(L), ios::cur);
OR
File.seekg(Position);
Line 2:
File.write((char*)&L, sizeof(L));
OR
File.write((char*)&L, sizeof(Library));
Question. A file named as "STUDENT.DAT" contains the student records, i.e. objects of class student. Write the command to open the file to update a student record. (Use suitable stream class and file mode(s).)
Answer:
fstream inof("STUDENT.DAT", ios::in | ios::out | ios::binary);
OR
fstream inof;
inof.open("STUDENT.DAT", ios::in | ios::out | ios::binary);
Question. A file named as "EMPLOYEE.DAT" contains the employee records, i.e. objects of class employee. Assuming that the file is just opened through the object FILE of fstream class, in the required file mode, write the command to position the put pointer to point to fifth record from the last record.
Answer: File.seekp(-5 * sizeof(employee), ios::end);
Question. A file named as "EMPLOYEE.DAT" contains the student records, i.e. objects of class employee. Assuming that the file is just opened through the object FILE of fstream class, in the required File mode, write the command to position the get pointer to point to eighth record from the beginning.
Answer: File.seekg(8 * sizeof(employee), ios::beg);
2 Marks Questions
```html
Question. Rewrite the following codes after removing errors, if any, in the following snippet. Explain each error.
#include<iostream.h>
void main( )
{
int x[5], *y, z[5]
for (i = 0; i < 5; i ++
{
x[i] = i;
z[i] = i + 3;
y = z;
x = y;
}
Answer: In this question first we have to write complete program after removing all the errors.
#include<iostream.h>
void main( )
{
int x[5], *y, z[5] ; // semi colon must be used here
for ( int i = 0; i < 5; i ++) // data type of i and closing ) should be there.
{
x[i] = i;
z[i] = i + 3;
*y = z; // wrong assignment ( integer to pointer)
x = *y; // wrong assignment ( Pointer to integer)
}
Question. Rewrite the following program after removing the error(s), if any. Underline each correction.
#include <iostream.h>
void main( )
{
int x, sum =0;
cin>>n;
for (x=1;x<100, x+=2)
if x%2=0
sum+=x;
cout<< “sum=” >>sum;
}
Answer: Corrected code:
#include <iostream.h>
void main()
{
int x, sum =0;
cin >> x ; // x in place of n
for (x=1; x<100 ; x+=2) //semicolon
if (x%2 == 0) // double =due to assignment, parentheses required
sum+=x;
cout<< "sum=" << sum; // <<
}
Question. Rewrite the following program after removing the syntactical error(s), if any Underline each correction:
#include <iostream.h>
void main( )
{
struct Book
{
char Book_name[20];
char Publisher_name[20];
int Price = 170;
} New Book;
gets(Book_name);
gets(Publisher_name);
}
Answer: #include <iostream.h>
#include<stdio.h>
void main( )
{
struct Book
{
char Book_name[20];
char Publisher_name[20];
int Price;
} Book New;
gets(New.Book_name);
gets(New.Publisher_name);
}
Question. Rewrite the following program after removing the syntactical errors (if any). Underline each correction.
#include [iostream.h]
class MEMBER
{
int Mno;float Fees;
PUBLIC:
void Register(){cin>>Mno>>Fees;}
void Display{cout<<Mno<<" : "<<Fees<<endl;}
};
void main()
{
MEMBER M;
Register();
M.Display();
}
Answer: #include <iostream.h>
class MEMBER
{
int Mno;float Fees;
public:
void Register(){cin>>Mno>>Fees;}
void Display(){cout<<Mno<<":"<<Fees<<endl;}
};
void main()
{
MEMBER M;
M.Register();
M.Display();
}
Question. Rewrite the following program after removing the syntactical errors (if any). Underline each correction.
#include <iostream.h>
struct Pixels
{ int Color,Style;}
void ShowPoint(Pixels P)
{ cout<<P.Color,P.Style<<endl;}
void main()
{
Pixels Point1=(5,3);
ShowPoint(Point1);
Pixels Point2=Point1;
Color.Point1+=2;
ShowPoint(Point2);
}
Answer: #include <iostream.h>
struct Pixels
{ int Color,Style;} ;
void ShowPoint(Pixels P)
{ cout<<P.Color<<P.Style<<endl;}
void main()
{
Pixels Point1={5,3};
ShowPoint(Point1);
Pixels Point2=Point1;
Point1.Color+=2;
ShowPoint(Point2);
}
Question. Rewrite the following program after removing the error(s), if any. Underline each correction.
#include <iostream.h>
void main( )
{
int x, sum =0;
cin>>n;
for (x=1;x<100, x+=2)
if x%2=0
sum+=x;
cout<< “sum=” >>sum;
}
Answer: #include <iostream.h>
void main( )
{
int x, sum =0;
cin >> x ; // x in place of n
for (x=1; x<100 ; x+=2) //semicolon
if x%2= = 0 // double =
sum+=x;
cout<< “sum=” << sum; // <<
}
Question. Will the following program execute successfully? If no, state the reason(s) :
#include<iostream.h>
#include<stdio.h>
#define int M=3;
void main( )
{
const int s1=10;
int s2=100;
char ch;
getchar(ch);
s1=s2*M;
s1+M = s2;
cout<<s1<<s2 ;
}
Answer: The program will not execute successfully due to the following errors:
1. `#define int M=3;` is an invalid preprocessor directive. It should be `#define M 3` or `const int M=3;`. If `#define int M=3;` is used, it will cause multiple syntax errors during compilation.
2. `getchar(ch);` is incorrect. `getchar()` does not take any arguments in C/C++. It should be used as `ch = getchar();` or `cin.get(ch);`. Also, `getchar()` is defined in `<stdio.h>`.
3. `s1` is a constant variable (`const int s1=10;`), so it cannot be modified. The line `s1=s2*M;` tries to modify `s1`, which is illegal.
4. `s1+M = s2;` is invalid. The left-hand side of an assignment operator must be an lvalue (modifiable memory location), but `s1+M` is an expression (rvalue).
Question. Rewrite the following program after removing the syntactical errors (if any). Underline each correction.
#include<iostream.h>
void main()
{
char arr{} = {12, 23, 34, 45};
int ptr = arr;
int val = *ptr; cout << *val << endl;
val = *ptr++; cout << val << endl;
val = *ptr : cout << val >> endl;
val = *++ptr; cout << val << endl;
}
Answer: include<iostream.h>
void main()
{
int arr[ ] = {12, 23, 34, 45};
int *ptr = arr;
int val = *ptr; cout << val << endl;
val = *ptr++; cout << val << endl;
val = *ptr ; cout << val << endl;
val = *++ptr; cout << val << endl;
}
Question. Rewrite the following program after removing the syntactical error (s), if any. Underline each correction.
#include<iostream.h>
const int dividor 5;
void main( )
{ Number = 15;
for(int Count=1;Count=<5;Count++,Number -= 3)
if(Number % dividor = 0)
{
cout<<Number / Dividor;
cout<<endl;
}
else
cout<<Number + Dividor <<endl;
}
Answer: #include<iostream.h>
const int dividor= 5;
void main( )
{
int Number = 15;
for(int Count=1;Count<=5;Count++,Number -= 3)
if(Number % dividor = = 0)
{
cout<<Number / Dividor;
cout<<endl;
}
else
cout<<Number + Dividor <<endl; }
Question. Rewrite the following program after removing the syntactical error(s) if any. Underline each correction.
#include<iostream.h>
void main( )
{
First = 10, Second = 30;
Jumpto(First;Second);
Jumpto(Second);
}
void Jumpto(int N1, int N2 = 20)
{
N1=N1+N2;
count<<N1>>N2;
}
Answer: #include<iostream.h>
void Jumpto(int N1,int N2=20); //Prototype missing
void main( )
{
int First = 10, Second = 30; //Data type missing
Jumpto(First , Second); //Comma to come instead of ;
Jumpto(Second);
}
void Jumpto(int N1, int N2=20)
{
N1=N1+N2;
cout<<N1<<N2; //Output operator << required
}
Question. Rewrite the following program after removing the syntactical error(s) if any. Underline each correction.
#include<iostream.h>
const int Max 10;
void main()
{
int Numbers[Max];
Numbers = {20,50,10,30,40};
for(Loc=Max-1;Loc>=10;Loc--)
cout>>Numbers[Loc];
}
Answer: #include<iostream.h>
const int Max = 10; //Constant Variable ‘Max’ must be initialized. Declaration Syntax Error
void main( )
{
int Numbers[Max]={20,50,10,30,40};
for(int Loc=Max-1;Loc>=0;Loc--)
cout<<Numbers[Loc];
}
Question. Rewrite the following program after removing the syntactical error(s), if any. Underline each correction.
#include<iostream.h>
const int Multiple 3;
void main( )
{
value = 15;
for(int Counter = 1;Counter = <5;Counter ++, Value -= 2)
if(Value%Multiple = = 0)
{
cout<<Value * Multiple;
cout<<end1;
}
else
cout<<Value + Multiple <<endl; }
Answer: #include<iostream.h>
const int Multiple=3;
void main( )
{
int Value = 15;
for(int Counter = 1;Counter <=5;Counter ++, Value -= 2)
if(Value%Multiple == 0)
{
cout<<Value * Multiple;
cout<<endl;
}
else
cout<<Value + Multiple <<endl;}
Question. Will the following program execute successfully? If not, state the reason(s).
#include<stdio.h>
void main( )
{ int s1,s2,num;
s1=s2=0;
for(x=0;x<11;x++)
{
cin<<num;
If(num>0)s1+=num;else s2=/num;
}
cout<<s1<<s2; }
Answer: The program will not execute successfully. Because some syntax errors are there in the program. They are
(i) cin and cout, stream objects used but iostream.h header file is not included in the program.
(ii) x is not declared, it should be declared as int.
(iii) With cin, we should use >> instead of <<.
(iv) The shorthand operator /=, is given wrongly as =/.
So the corrected program is as follows:
#include<iostream.h>
void main( )
{ int s1,s2,num;
s1=s2=0;
for(int x=0;x<11;x++)
{
cin>>num;
if(num>0)s1+=num;else s2/=num;
}
cout<<s1<<s2; }
Question. Identify the errors if any. Also give the reason for errors.
#include<iostream.h>
void main()
{
const int i =20;
const int * ptr=&i;
(*ptr)++;
int j=15;
ptr =&j;
}
Answer: #include<iostream.h>
void main()
{
const int i=20;
int * ptr=&i;
(*ptr)++; //can not modify a const object
int j=15;
ptr =&j;
}
Question. Identify the errors if any. Also give the reason for errors.
#include<iostream.h>
void main()
{
const int i =20;
const int * const ptr=&i;
(*ptr)++;
int j=15;
ptr =&j;
}
Answer: #include<iostream.h>
void main()
{
const int i =20;
const int * const ptr=&i; //can not modify a const object
(*ptr)++;
int j=15;
ptr =&j; //can not modify a const pointer
}
Question. Identify errors on the following code segment
float c[ ] ={ 1.2,2.2,3.2,56.2};
float *k,*g;
k=c;
g=k+4;
k=k*2;
g=g/2;
cout<<”*k=”<<*k<<”*g=”<<*g;
Answer: The error statements are
k=k*2; g=g/2; as pointer multiplication and division is not possible.
Question. Write the output of the following program.
void main( )
{
int x=5,y=5;
cout<<x- -;
cout<<”,”;
cout<<- - x;
cout<<”,”;
cout<<y- -<<”,”<<- -y;
}
Answer: 5,3,4,4
Question. Predict the output of the following code:
# include<iostream.h>
#include<conio.h>
void main()
{
int arr[] = {12, 23, 34, 45};
int *ptr = arr;
int val = *ptr; cout << val << endl;
val = *ptr++; cout << val << endl;
val = *ptr; cout << val << endl;
val = *++ptr; cout << val << endl;
}
Answer: 12
12
23
34
Question. Find the output of the following code.
#include<iostream.h>
#include<conio.h>
void main()
{
int arr[] = {12, 23, 34, 45};
int *ptr = arr;
int val = *ptr; cout << val << endl;
val = *ptr++; cout << val << endl;
val = *ptr; cout << val << endl;
val = *++ptr; cout << val << endl;
val = ++*ptr; cout << val << endl;
}
Answer: 12
12
23
34
35
Question. #include<iostream.h>
#include<conio.h>
void main()
{
int arr[] = {12, 23, 34, 45};
int *ptr = arr;
int val = *ptr; cout << val << endl;
val = (*ptr)++; cout << val << endl;
val = *ptr; cout << val << endl;
val = *++ptr; cout << val << endl;
}
Answer: 12
12
13
23
Question. #include<iostream.h>
#include<conio.h>
void main()
{
int arr[] = {2, 33, 44, 55};
int *ptr = arr;
int val = *ptr; cout << val << endl;
val = *++ptr ; cout << val << endl;
val = *ptr; cout << val << endl;
val = * ptr++; cout << val << endl;
}
Answer: 2
33
33
33
Question. Write the output of the following program:
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr( );
int a =32;
int *ptr = &a;
char ch = ‘A’;
char *cho=&ch;
cho+=a; // it is simply adding the addresses.
*ptr + = ch;
cout<< a << “” <<ch<<endl;
}
Answer: 97A
Question. Write the output of the following program:
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr( );
int a =32;
int *ptr = &a;
char ch = ‘A’;
char *cho=&ch;
*cho+=a; // it is adding the values.
cout<< a << “” <<ch<<endl;
}
Answer: The meaning of line *cho+=a is:
*cho= *cho +32
= A+32
=97
=’a’ ( ASCII value of character a)
cho contains the address of ch so ch =’a’;
Therefore output would be : 32a
Question. Write the output of the following program:
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr( );
int a =32;
int *ptr = &a;
char ch = 'A';
char *cho=&ch;
*cho+=a;
*ptr += ch;
cout<< a << "" <<ch<<endl;
}
Answer: 129a
ch =97 ( from *cho+=a)
*ptr+=ch
*ptr= *ptr+ch
= 32+ ‘a’ (Character a)
=32+97
=129
Since *ptr or variable a both are same so variable a =129 and ch = ‘a’.
Question. Write a function in C++ to print the count of the word the as an independent word in a text file STORY.TXT.
For example, if the content of the file STORY.TXT is
There was a monkey in the zoo.
The monkey was very naughty.
Then the output of the program should be 2.
Answer: void thewordCount()
{
ifstream Fil(“STORY.TXT”);
char String[20];
int C=0;
while(Fil)
{
Fil>>String;
if(strcmpi(String,”the”)==0)//case insensitive
C=C+1;
}
cout<<C<<endl;
Fil.close();
}
Question. Assume a text file “coordinate.txt” is already created. Using this file create a C++ function to count the number of words having first character capital.
Example:
Do less Thinking and pay more attention to your heart. Do Less Acquiring and pay more Attention to what you already have. Do Less Complaining and pay more Attention to giving. Do Less criticizing and pay more Attention to Complementing. Do less talking and pay more attention to SILENCE.
Output will be : Total words are 16
Answer: Hint: Use isupper(word[0])
Question. Write a function in C++ to count the number of lines present in a text file “STORY.TXT”.
Answer: void CountLine()
{
ifstream FIL(“STORY.TXT”);
int LINES=0;
char STR[80];
while (FIL.getline(STR,80))
LINES++;
cout<<”No. of Lines:”<<LINES<<endl;
FIL.close();
}
Question. Write a function in C++ to count the number of alphabets present in a text file “NOTES.TXT”.
Answer: void CountAlphabet()
{
ifstream FIL(“NOTES.TXT”);
int CALPHA=0;
char CH=FIL.get();
while (FIL)
{
if (isalpha(CH)) CALPHA++;
CH=FIL.get();
}
cout<<”No. of Alphabets:”<<CALPHA<<endl;
FIL.close();
}
Question. Write a function in C++ to write the characters entered through the keyboard into the file“myfile.txt”, until a ‘#’ character is entered.
Answer: void entercharacter{
ofstream fout;
fout.open("string.txt");
if(!fout) {
cout<<"\n Unable to open file";
exit(1);
}
char c;
while((c=cin.get())!='#') // or while((c=getchar())!= ‘#’)
{
fout.put(c);
}
fout.close();
}
Question. Answer the questions (i) and (ii) after going through the following class:
class Seminar
{
int Time;
public:
Seminar() //Function 1
{
Time=30;cout<<"Seminar starts now"<<endl;
}
void Lecture() //Function 2
{
cout<<"Lectures in the seminar on"<<endl;
}
Seminar(int Duration) //Function 3
{
Time=Duration;cout<<"Seminar starts now"<<endl;
}
~Seminar()
//Function 4
{
cout<<"Vote of thanks"<<endl;
}
};
i) In Object Oriented Programming, what is Function 4 referred as and when does it get invoked/ called?
ii) In Object Oriented Programming, which concept is illustrated by Function 1 and Function 3 together? Write an example illustrating the calls for these functions.
Answer: i) Destructor, it is invoked as soon as the scope of the object gets over.
ii) Constructor Overloading (or Function Overloading or Polymorphism)
Seminar S1; //Function 1
Seminar S2(90); //Function 3
Question. Answer the questions (i) and (ii) after going through the following program:
#include<iostream.h>
#include<string.h>
class Bazar
{
char Type[20];
char Product[20];
int Qty;
float Price;
Bazar() //Function 1
{
strcpy (Type,”Electronic”);
strcpy (Product,”Calculator”);
Qty = 10;
Price=225;
}
public:
void Disp( ) //Function 2
{
cout<<Type<<”-“<<Product<<”:“<<Qty
<<”@“<<Price<<endl;
}
};
void main( )
{
Bazar B; //Statement 1
B.Disp(); //Statement 2
}
(i) Will Statement 1 initialize all the data members for object B with the values given in the Function 1? (Yes OR No). Justify your answer suggesting the correction(s) to be made in the above code.
(ii) What shall be the possible output when the program gets executed? (Assuming, if required – the suggested correction(s) are made in the program)
Answer: (i) No, since the constructor Bazar has been defined in private section or constructor has not been defined in public section.
Suggested Correction: Constructor Bazar() to be defined in public
(ii)If the constructor is defined as a public member, the following output shall be generated:
Electronic-Calculator:10@225
Question. Given a class as follows:
class Match
{
int Time;
int Points;
public:
Match(int y, int p) //Conctructor1
{
Time=y;
Points =p;
}
Match(Match &M); // Constructor 2
};
(i) Create an object, such that it invokes Constructor 1.
(ii) Write complete definition for Constructor 2.
Answer: (i) Match M1(0,0);
(ii) Match (Match &M)
{
Time=M.Time;
Points=M.Points;
}
Question. Answer the questions (i) and (ii) after going through the following class:
class player
{
int health;
int age;
public:
player() { health=7; age=17 } //Constructor1
player(int h, int a) {health =h; age = a ; } //Constructor2
player( player &p) { } //Constructor3
~player() { cout<<”Memory Free”; } //Destructor
};
void main(){
player p1(9,26); //Statement1
player p3 = p1; //Statement3
}
(i) When p3 object created specify which constructor invoked and why?
(ii) Write complete definition for Constructor3?
Answer: (i)When p3 object created , Constructor 3 will be invoked since it is copy constructor.
(ii) complete definition for Constructor 3
player( player &p)
{
health = p.health;
age= p.age;
}
4 Marks Questions
Question. Define a class TEST in C++ with following description:
Private Members
• TestCode of type integer
• Description of type string
• NoCandidate of type integer
• CenterReqd (number of centers required) of type integer
• A member function CALCNTR() to calculate and return the number of centers as (NoCandidates/100+1)
Public Members
• A function SCHEDULE() to allow user to enter values for TestCode, Description, NoCandidate & call function CALCNTR() to calculate the number of Centres
• A function DISPTEST() to allow user to view the content of all the data members
Answer:
#include <iostream>
#include <string>
using namespace std;
class TEST {
int TestCode;
string Description;
int NoCandidate;
int CenterReqd;
void CALCNTR() {
CenterReqd = (NoCandidate / 100) + 1;
}
public:
void SCHEDULE();
void DISPTEST();
};
void TEST::SCHEDULE() {
cout << "Enter Test Code: ";
cin >> TestCode;
cout << "Enter Description: ";
cin.ignore();
getline(cin, Description);
cout << "Enter Number of Candidates: ";
cin >> NoCandidate;
CALCNTR();
}
void TEST::DISPTEST() {
cout << "Test Code: " << TestCode << endl;
cout << "Description: " << Description << endl;
cout << "Number of Candidates: " << NoCandidate << endl;
cout << "Centers Required: " << CenterReqd << endl;
}
In simple words: This class keeps track of exam tests. It takes input from the user and uses a private function to calculate how many exam centers are needed.
Exam Tip: Private helper functions like CALCNTR() can only be called from inside other member functions of the same class. Do not try to call them from main().
Question. Define a class in C++ with following description:
Private Members
• A data member Flight number of type integer
• A data member Destination of type string
• A data member Distance of type float
• A data member Fuel of type float
• A member function CALFUEL() to calculate the value of Fuel as per the following criteria:
Distance | Fuel
<=1000 | 500
more than 1000 and <=2000 | 1100
More than 2000 | 2200
Public Members
• A function FEEDINFO() to allow user to enter values for Flight Number, Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel
• A function SHOWINFO() to allow user to view the content of all the data members
Answer:
#include <iostream>
#include <string>
using namespace std;
class FLIGHT {
int Flight_number;
string Destination;
float Distance;
float Fuel;
void CALFUEL();
public:
void FEEDINFO();
void SHOWINFO();
};
void FLIGHT::CALFUEL() {
if (Distance <= 1000) {
Fuel = 500;
} else if (Distance <= 2000) {
Fuel = 1100;
} else {
Fuel = 2200;
}
}
void FLIGHT::FEEDINFO() {
cout << "Enter Flight Number: ";
cin >> Flight_number;
cout << "Enter Destination: ";
cin.ignore();
getline(cin, Destination);
cout << "Enter Distance: ";
cin >> Distance;
CALFUEL();
}
void FLIGHT::SHOWINFO() {
cout << "Flight Number: " << Flight_number << endl;
cout << "Destination: " << Destination << endl;
cout << "Distance: " << Distance << endl;
cout << "Fuel Assigned: " << Fuel << endl;
}
In simple words: This class represents a flight. It automatically calculates the necessary fuel based on the travel distance using an internal function.
Exam Tip: Be careful with conditional structures in CALFUEL(). Ensure you use correct boundary values like <= to match the given ranges exactly.
Question. Define a class Clothing in C++ with the following descriptions:
Private Members:
Code of type string
Type of type string
Size of type integer
Material of type string
Price of type float
A function Calc_Price() which calculates and assigns the value of Price as follows:
For the value of Material as “COTTON”
Type | Price (Rs.)
TROUSER | 1500
SHIRT | 1200
For Material other than “COTTON” the above mentioned Price gets reduced by 25%.
Public Members:
A constructor to assign initial values of Code, Type and Material with the word “NOT ASSIGNED” and Size and Price with 0.
A function Enter () to input the values of the data members Code, Type, Size and Material and invoke the CalcPrice() function.
A function Show () which displays the content of all the data members for a Clothing.
Answer:
#include <iostream>
#include <string>
using namespace std;
class Clothing {
string Code;
string Type;
int Size;
string Material;
float Price;
void Calc_Price();
public:
Clothing();
void Enter();
void Show();
};
Clothing::Clothing() {
Code = "NOT ASSIGNED";
Type = "NOT ASSIGNED";
Material = "NOT ASSIGNED";
Size = 0;
Price = 0;
}
void Clothing::Calc_Price() {
if (Type == "TROUSER") {
Price = 1500;
} else if (Type == "SHIRT") {
Price = 1200;
} else {
Price = 0;
}
if (Material != "COTTON") {
Price = Price * 0.75; // Apply a 25% price reduction
}
}
void Clothing::Enter() {
cout << "Enter Code: ";
cin >> Code;
cout << "Enter Type (TROUSER/SHIRT): ";
cin >> Type;
cout << "Enter Size: ";
cin >> Size;
cout << "Enter Material: ";
cin >> Material;
Calc_Price();
}
void Clothing::Show() {
cout << "Code: " << Code << endl;
cout << "Type: " << Type << endl;
cout << "Size: " << Size << endl;
cout << "Material: " << Material << endl;
cout << "Price: " << Price << endl;
}
In simple words: This class handles clothing inventory details. It defaults new items to "NOT ASSIGNED" and applies a 25% price reduction if the material is not cotton.
Exam Tip: Remember that constructors do not have a return type, not even void. Make sure to initialize all members exactly as specified in the problem statement.
Question. Define a class Travel in C++ with the description given below:
Private Members:
T_Code of type string
No_of_Adults of type integer
No_of_Children of type integer
Distance of type integer
TotalFare of type float
Public Members:
A constructor to assign initial values as follows :
T_Code with the word “NULL”
No_of_Adults as 0
No_of_Children as 0
Distance as 0
TotalFare as 0
A function AssignFare( ) which calculates and assigns the value of the data member TotalFare as follows :
For each Adult
Fare (Rs) | For Distance (Km)
500 | >=1000
300 | <1000 & >=500
200 | <500
For each Child the above Fare will be 50% of the Fare mentioned in the above table.
For example :
If Distance is 750, No_of_Adults = 3 and No_of_Children = 2
Then TotalFare should be calculated as
No_of_Adults * 300 + No_of_Children * 150
i.e. 3 * 300 + 2 * 150 = 1200
• A function EnterTraveK ) to input the values of the data members T_Code, No_of_Adults, No_of_Children and Distance; and invoke the AssignFare( ) function.
• A function ShowTraveK) which displays the content of all the data members for a Travel.
Answer:
#include <iostream>
#include <string>
using namespace std;
class Travel {
string T_Code;
int No_of_Adults;
int No_of_Children;
int Distance;
float TotalFare;
void AssignFare();
public:
Travel();
void EnterTraveK();
void ShowTraveK();
};
Travel::Travel() {
T_Code = "NULL";
No_of_Adults = 0;
No_of_Children = 0;
Distance = 0;
TotalFare = 0;
}
void Travel::AssignFare() {
float adultFare = 0;
if (Distance >= 1000) {
adultFare = 500;
} else if (Distance >= 500) {
adultFare = 300;
} else {
adultFare = 200;
}
TotalFare = (No_of_Adults * adultFare) + (No_of_Children * (adultFare * 0.5));
}
void Travel::EnterTraveK() {
cout << "Enter Travel Code: ";
cin >> T_Code;
cout << "Enter Number of Adults: ";
cin >> No_of_Adults;
cout << "Enter Number of Children: ";
cin >> No_of_Children;
cout << "Enter Distance: ";
cin >> Distance;
AssignFare();
}
void Travel::ShowTraveK() {
cout << "Travel Code: " << T_Code << endl;
cout << "Adults: " << No_of_Adults << endl;
cout << "Children: " << No_of_Children << endl;
cout << "Distance: " << Distance << endl;
cout << "Total Fare: " << TotalFare << endl;
}
In simple words: This class calculates travel fares based on travel distance. Children receive a 50% discount on the adult fare.
Exam Tip: When a question contains typos (like EnterTraveK), it's wise to use the exact function names requested by the examiner to avoid any loss of marks.
Question. Answer the questions (i) to (iv) based on the following code :
class CUSTOMER
{
int Cust_no;
char Cust_Name[20];
protected:
void Register();
public:
CUSTOMER();
void Status();
};
class SALESMAN
{
int Salesman_no;
char Salesman_Name[20];
protected:
float Salary;
public:
SALESMAN();
void Enter();
void Show();
};
class SHOP : private CUSTOMER , public SALESMAN
{
char Voucher_No[10];
char Sales_Date[8];
public:
SHOP();
void Sales_Entry();
void Sales_Detail();
};
(iii) Write the names of data members which are accessible from objects belonging to class CUSTOMER.
(iv) Write the names of all the member functions which are accessible from objects belonging to class SALESMAN.
(v) Write the names of all the members which are accessible from member functions of class SHOP.
(iv) How many bytes will be required by an object belonging to SHOP?
Answer:
(iii) No data members from the CUSTOMER class can be reached through its objects because all of them are private.
(iv) The public member functions Enter() and Show() are accessible from objects of the SALESMAN class.
(v) The members accessible from member functions of class SHOP are:
- Data members: Voucher_No, Sales_Date (own members), and Salary (protected member from class SALESMAN).
- Member functions: Sales_Entry(), Sales_Detail() (own public members), Enter(), Show() (public members of SALESMAN), and Register(), Status() (protected/public members of CUSTOMER).
(iv) An object of class SHOP requires 66 bytes of memory (assuming 2 bytes for int and 4 bytes for float).
In simple words: Objects can only access public members of a class. Member functions inside a derived class can access protected members of base classes, but not private ones.
Exam Tip: Private data members of any class are completely inaccessible to its objects. Only public components are reachable from outside.
Question. Answer the questions (i) to (iv) based on the following:
class PUBLISHER
{
char Pub[12];
double Turnover;
protected:
void Register();
public:
PUBLISHER();
void Enter();
void Display();
};
class BRANCH
{
char CITY[20];
protected:
float Employees;
public:
BRANCH();
void Haveit();
void Giveit();
};
class AUTHOR : private BRANCH , public PUBLISHER
{
int Acode;
char Aname[20];
float Amount;
public:
AUTHOR();
void Start();
void Show();
};
(i) Write the names of data members, which are accessible from objects belonging to class AUTHOR.
(ii) Write the names of all the member functions which are accessible from objects belonging to class BRANCH.
(iii) Write the names of all the members which are accessible from member functions of class AUTHOR.
(iii) How many bytes will be required by an object belonging to class AUTHOR?
Answer:
(i) There are no data members accessible directly using an object of the AUTHOR class.
(ii) The public member functions Haveit() and Giveit() are accessible from objects of the BRANCH class.
(iii) The members accessible from member functions of class AUTHOR are:
- Data members: Employees (from BRANCH), along with Acode, Aname, and Amount (from AUTHOR).
- Member functions: Register(), Enter(), Display() (from PUBLISHER), Haveit(), Giveit() (from BRANCH), and Start(), Show() (from AUTHOR).
(iii) A single object of the AUTHOR class requires 70 bytes of storage (assuming 2 bytes for int and 4 bytes for float).
In simple words: Class AUTHOR privately inherits from BRANCH and publicly inherits from PUBLISHER. This controls which methods and attributes are visible outside or inside.
Exam Tip: Note the inheritance modes: private inheritance turns all inherited public/protected members of the base class into private members of the derived class.
Question. Answer the questions (i) to (iv) based on the following code:
class Dolls
{
char DCode[5];
protected:
float Price ;
void CalcPrice(float);
public:
Dolls( );
void DInput( );
void DShow( );
};
class SoftDolls: public Dolls
{
char SDName[20];
float Weight;
public:
SoftDolls( );
void SDInput( );
void SDShow( );
};
class ElectronicDolls: public Dolls
{
char EDName[20];
char BatteryType[10];
int Battieries;
public:
ElectronicDolls ( );
void EDInput( );
void EDShow( );
};
(i) Which type of Inheritance is shown in the above example?
(ii) How many bytes will be required by an object of the class ElectronicDolls?
(iii) Write name of all the data members accessible from member functions of the class SoftDolls.
(iv) Write name of all the member functions accessible by an object.
Answer:
(i) This is an example of hierarchical inheritance, since multiple child classes derive from a single base class.
(ii) An object belonging to ElectronicDolls requires 41 bytes of memory (with 2 bytes for int and 4 bytes for float).
(iii) The accessible data members from class SoftDolls are SDName, Weight, and the inherited protected member Price.
(iv) Assuming an object of class ElectronicDolls, the accessible member functions are EDInput(), EDShow(), DInput(), and DShow().
In simple words: Hierarchical inheritance means two or more classes inherit from one parent class. Protected members of the parent are accessible to its child classes.
Exam Tip: In hierarchical inheritance, sister classes (like SoftDolls and ElectronicDolls) cannot access each other's members.
Question. Consider the following class declaration and answer the question below :
class university {
int noc;
protected:
char uname[25];
public:
university();
char state[25];
void enterdata();
void displaydata();
};
class college:public university{
int nod;
char cname[25];
protected:
void affiliation();
public:
college();
void enrol(int ,int);
void show();
};
class department:public college{
char dname[25];
int nof;
public:
department();
void display();
void input();
};
(i) Which class’s constructor will be called first at the time of declaration of an object of class department?
(ii) How many bytes does an object belonging to class department require?
(iii) Name the member function(s), which are accessed from the object of class department.
(iv) Name the data member, which are accessible from the object of class college.
Answer:
(i) The constructor of the university class is executed first, as it is the uppermost base class in the hierarchy.
(ii) An object of class department needs 106 bytes of memory space (assuming int occupies 2 bytes).
(iii) The accessible member functions from the object of class department are display(), input(), enrol(), show(), enterdata(), and displaydata().
(iv) The only public data member accessible from an object of class college is state.
In simple words: In multilevel inheritance, constructors are called from top to bottom (base to derived). Only public members can be accessed using an object.
Exam Tip: Note that although char state[25] is a data member, it is declared in the public section of university, making it accessible via objects.
Question. Answer the questions(i) to (iv) based on the following :
class cloth
{
char category[5];
char description[25];
protected:
float price;
public:
void Entercloth( );
void dispcloth( );
};
class Design : protected cloth
{
char design[21];
protected:
float cost_of_cloth;
public:
int design_code;
Design( );
void Enterdesign( );
void dispdesign( );
};
class costing : public cloth
{
float designfee;
float stiching;
float cal_cp( );
protected:
float costprice;
float sellprice;
public:
void Entercost( );
void dispcost( );
costing ( ) { };
};
(i) Write the names of data members which are accessible from objects belonging to class cloth.
(ii) Write the names of all the members which are accessible from objects belonging to class Design.
(iii) Write the names of all the data members which are accessible from member functions of class costing.
(iv) How many bytes will be required by an object belonging to class Design?
Answer:
(i) There are no data members accessible from objects of the cloth class.
(ii) The members accessible via Design objects are the public variable design_code and the public methods Enterdesign() and dispdesign().
(iii) The accessible data members inside costing are designfee, stiching, costprice, sellprice, and the inherited protected variable price.
(iv) An object of class Design requires 61 bytes of memory (with 2 bytes for int and 4 bytes for float).
In simple words: Under protected inheritance, public and protected members of the parent class become protected in the child class, meaning they can only be used by the child class's internal code, not by outside objects.
Exam Tip: Protected inheritance makes the base class's public methods protected in the derived class, so they cannot be accessed by derived class objects.
Question. Answer the questions(i) to (iv) based on the following :
class Regular
{
char SchoolCode[10];
public:
void InRegular( );
void OutRegular( );
};
class Distance
{
char StudyCentreCode[5];
public:
void InDistance( );
void OutDistance( );
};
class Course : public Regular, private Distance
{
char Code[5];
float Fees;
int Duration;
public:
void InCourse( );
void OutCourse( );
};
(i) Which type of Inheritance is shown in the above example?
(ii) Write names of all the member functions accessible from Outcourse function of class Course.
(iii) Write name of all the members accessible through an object of the Class Course.
(iv) Is the function InRegular( ) accessible inside the function InDistance ( )? Justify your answer.
Answer:
(i) This is multiple inheritance because a single child class inherits from more than one parent class.
(ii) The member functions accessible from OutCourse() are InCourse(), InDistance(), OutDistance(), InRegular(), and OutRegular().
(iii) The members accessible via a Course object are InCourse(), OutCourse(), InRegular(), and OutRegular().
(iv) Direct access is not allowed because Regular and Distance are independent classes. However, it can be accessed by creating an instance of Regular inside InDistance() and calling it via that instance.
In simple words: Multiple inheritance lets one class derive from two or more parent classes at once. Private inheritance hides the parent's methods from the outside world.
Exam Tip: In multiple inheritance, pay close attention to the access specifiers of each base class (e.g., public Regular vs private Distance) as they alter visibility.
Question. Define a class named ADMISSION in C++ with the following descriptions:
Private members:
AD_NO integer (Ranges 10 - 2000)
NAME Array of characters (String)
CLASS Character
FEES Float
Public Members:
• Function Read_Data ( ) to read an object of ADMISSION type
• Function Display( ) to display the details of an object
• Function Draw_Nos ( ) to choose 2 students randomly and display the details. Use random function to generate admission nos to match with AD_NO.
Answer:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class ADMISSION {
int AD_NO;
char NAME[50];
char CLASS;
float FEES;
public:
void Read_Data();
void Display() const;
static void Draw_Nos(ADMISSION students[], int size);
};
void ADMISSION::Read_Data() {
cout << "Enter Admission Number (10 - 2000): ";
cin >> AD_NO;
cout << "Enter Name: ";
cin.ignore();
cin.getline(NAME, 50);
cout << "Enter Class: ";
cin >> CLASS;
cout << "Enter Fees: ";
cin >> FEES;
}
void ADMISSION::Display() const {
cout << "Admission No: " << AD_NO << endl;
cout << "Name: " << NAME << endl;
cout << "Class: " << CLASS << endl;
cout << "Fees: " << FEES << endl;
}
void ADMISSION::Draw_Nos(ADMISSION students[], int size) {
if (size < 2) {
cout << "Not enough students to draw." << endl;
return;
}
srand(time(0));
int count = 0;
while (count < 2) {
int rand_ad_no = 10 + rand() % 1991; // Generates number in range [10, 2000]
for (int i = 0; i < size; ++i) {
if (students[i].AD_NO == rand_ad_no) {
cout << "\n--- Randomly Selected Student ---" << endl;
students[i].Display();
count++;
break;
}
}
}
}
In simple words: This class stores student admission details and includes a helper function to randomly choose and print the details of two matching students.
Exam Tip: Use srand(time(0)) and rand() from <cstdlib> and <ctime> to generate random values, and ensure your random range matches the specified constraints.
Question. Define a class named MOVIE in C++ with the following description:
Private members
HALL_NO integer
MOVIE_NAME Array of characters (String)
WEEK integer (Total number of weeks the same movie is shown)
WEEK_COLLECTION Float
TOTAL_COLLECTION Float
Public Members
• Function Read_Data( ) to read an object of ADMISSION type
• Function Display( ) to display the details of an object
• Function Update( ) to update the total collection and Weekly collection once in a week changes. Total collection will be incremented by Weekly collection and Weekly collection is made Zero
Answer:
#include <iostream>
using namespace std;
class MOVIE {
int HALL_NO;
char MOVIE_NAME[50];
int WEEK;
float WEEK_COLLECTION;
float TOTAL_COLLECTION;
public:
void Read_Data();
void Display() const;
void Update();
};
void MOVIE::Read_Data() {
cout << "Enter Hall Number: ";
cin >> HALL_NO;
cout << "Enter Movie Name: ";
cin.ignore();
cin.getline(MOVIE_NAME, 50);
cout << "Enter Week Number: ";
cin >> WEEK;
cout << "Enter Weekly Collection: ";
cin >> WEEK_COLLECTION;
cout << "Enter Total Collection: ";
cin >> TOTAL_COLLECTION;
}
void MOVIE::Display() const {
cout << "Hall No: " << HALL_NO << endl;
cout << "Movie Name: " << MOVIE_NAME << endl;
cout << "Week: " << WEEK << endl;
cout << "Weekly Collection: " << WEEK_COLLECTION << endl;
cout << "Total Collection: " << TOTAL_COLLECTION << endl;
}
void MOVIE::Update() {
TOTAL_COLLECTION += WEEK_COLLECTION;
WEEK_COLLECTION = 0;
WEEK++;
}
In simple words: This class represents a movie. It tracks collections over time and has an update method that moves weekly sales into the total pool and resets the weekly value.
Exam Tip: When implementing functions like Update(), make sure you modify the member variables exactly as specified (e.g., adding weekly collection to total collection and setting the weekly collection back to zero).
Question. Consider the following declarations and answer the questions given below:
class Mydata
{ protected:
int data;
public:
void Get_mydata(int);
void Manip_mydata(int);
void Show_mydata(int);
Mydata( );
~Mydata( );
};
class Personal_data
{
protected:
int data1;
public:
void Get_personaldata(int);
void Show_personaldata(int);
Personal_data1( );
~Personal_data1( );
};
class Person: public Mydata, Personal_data
{
public:
void Show_person(void);
Person( );
~Person( );
};
i) How many bytes will be required by an object belonging to class Person?
ii) Which type of inheritance is depicted in the above example?
iii) List the data members that can be accessed by the member function Show_person( ).
iv) What is the order of constructor execution at the time of creating an object of class Person?
Answer:
i) An object of class Person requires 4 bytes of memory (assuming 2 bytes for each integer).
ii) This is an example of multiple inheritance.
iii) The member function Show_person() can access the protected data members data (from Mydata) and data1 (from Personal_data).
iv) The execution order of the constructors is: Mydata(), followed by the constructor of Personal_data, and then Person().
In simple words: Class Person inherits from two different parent classes at the same time. The parent constructors are called first, in the order they are inherited, before the child class constructor runs.
Exam Tip: Note that if no access specifier is specified during inheritance (like Personal_data), C++ defaults to private inheritance for classes.
Question. Answer the questions (i) to (iv) based on the following:
class Book
{
int year_publication;
char title[25];
float price;
public:
Book( );
void input_data( );
void output_data( );
};
class Tape
{
char comp_name[20];
protected:
char comp_addr[35];
public:
Tape( );
void read_data( );
void show_data( );
};
class Publication : private Book , public Tape
{
int no_copies;
public:
Publication( );
void Pub_Entry( );
void Pub_Detail( );
};
(i) Write the names of data members which are accessible from objects belonging to class Publication.
(ii) Write the names of all the member functions which are accessible from objects belonging to class Tape.
(iii) Write in which order the constructors will be invoked when an object of class Publication is created .
(iv) How many bytes will be required by an object belonging to class Publication?
Answer:
(i) There are no data members accessible directly through objects of the Publication class.
(ii) The public member functions read_data() and show_data() can be accessed from any Tape class object.
(iii) When an object of class Publication is created, the constructors are invoked in the order of: Book(), Tape(), and then Publication().
(iv) An object of class Publication requires 88 bytes of memory space.
In simple words: Class Publication inherits from Book and Tape. Constructors execute from the parent classes down to the child class.
Exam Tip: Base class constructors are called in the order they appear in the inheritance list of the derived class declaration, not in the order of their initialization list.
Question. Answer the questions (i) to (iv) based on the following code:
class vehicle
{
int wheels;
protected:
int passenger;
public:
void inputdata( );
void outputdata( );
};
class heavyvehicle : protected vehicle
{
int diesel_petrol;
protected:
int load;
public:
void readdata(int, int);
void writedata( );
};
class bus : private heavyvehicle
{
char make[20];
public:
void fetchdata( );
void displaydata( );
};
i) Name the base class and derived class of heavyvehicle class.
ii) Name the data member(s) that can be accessed from the function displaydata( ).
iii) How many bytes will be required by an object of vehicle and heavyvehicle classes respectively?
iv) Is the member function outputdata( ) accessible to the objects of the class heavyvehicle?
Answer:
i) For class heavyvehicle, the parent/base class is vehicle and the child/derived class is bus.
ii) Inside displaydata(), the accessible data members are make, load, and passenger.
iii) An object of class vehicle requires 4 bytes, while an object of class heavyvehicle requires 8 bytes (assuming 2 bytes per int).
iv) No, the function outputdata() becomes protected in heavyvehicle due to protected inheritance, meaning objects of heavyvehicle cannot access it.
In simple words: Protected inheritance changes the public methods of the parent class into protected methods in the child class, hiding them from external objects.
Exam Tip: Always specify the memory size based on standard integer sizes (typically 2 bytes in Turbo C++ environments, which these classic questions assume).
Question. Consider the following declarations and answer the questions given below:
class Animal
{
int leg;
protected:
int tail;
public:
void INPUT (int );
void OUT ( );
};
class wild : private Animal
{
int carniv;
protected:
int teeth;
Public:
void INDATA (int, int );
void OUTDATA( );
};
class pet : public Animal
{
int herbiv;
public:
void Display (void);
};
(i) Name the base class and derived class of the class wild.
(ii) Name the data member(s) that can be accessed from function Display ( ).
(iii) Name the member function(s), which can be accessed from the objects of class pet.
(iv) Is the member function OUT ( ) accessible by the objects of the class wild?
Answer:
(i) The base class of wild is Animal, and there are no classes derived from wild.
(ii) Inside the Display() function of class pet, the accessible data members are herbiv and tail.
(iii) The member functions accessible from an object of class pet are Display(), INPUT(), and OUT().
(iv) No, since wild inherits from Animal privately, OUT() is private in wild and cannot be called by its objects.
In simple words: Public inheritance keeps the parent's public methods public in the child, while private inheritance turns them private, blocking outside access.
Exam Tip: Note that private members of a base class (like leg) are never accessible in any derived class, regardless of the inheritance type.
Question. Answer the questions (i) to (iv) based on the following class declaration:
class Medicine
{
char category[10];
char Date_of_Manufacture[10];
char Date_Of_Expiry[10];
protected:
char company[20];
public:
int x,y;
Medicine( );
void Enter( );
void Show( );
};
class Tablet :protected Medicine
{
protected:
char tablet_name[30];
char volume_label[20];
void disprin( );
public:
float price;
Tablet( );
void enterdet( );
void showdet( );
};
class PainReliever : public Tablet
{
int Dosage_units;
long int tab;
char effects[20];
protected:
int use_within_Days;
public :
PainReliever( );
void enterpr( );
showpr( );
};
(i) How many bytes will be required by an object of class Drug and an object of class PainReliever respectively.
(ii) Write names of all the data members which are accessible from the object of class PainReliever.
(iii) Write names of all member functions which are accessible from objects of class PianReliever.
(iv) Write the names of all the data members which are accessible from the functions enterpr().
Answer:
(i) Assuming "Drug" refers to the Medicine class, an object of Medicine requires 54 bytes and an object of PainReliever requires 136 bytes.
(ii) The only data member accessible from an object of class PainReliever is the public variable price (inherited from Tablet).
(iii) The member functions accessible from objects of PainReliever are enterpr(), showpr(), enterdet(), and showdet().
(iv) The data members accessible from the function enterpr() are Dosage_units, tab, effects, use_within_Days, tablet_name, volume_label, price, company, x, and y.
In simple words: Member functions of a derived class can access protected and public members of all parent classes in its inheritance line, but objects can only access public members.
Exam Tip: Note the cascading effect of protected inheritance: public members of Medicine became protected in Tablet, meaning they cannot be accessed by PainReliever objects.
Question. Answer the questions (i) to (iv) based on following code:
class World
{
int H;
protected:
int s;
public:
void INPUT(int);
void OUTPUT( );
};
class Country : private World
{
int T;
protected:
int U;
public :
void INDATA(int, int);
void OUTDATA();
};
class State : public Country
{
int M;
public :
void DISPLAY(void);
};
(i) Name the base class and derived class of the class Country.
(ii) Name the data member that can be accessed from function DISPLAY( )
(iii) Name the member functions, which can be accessed from the objects of class State.
(iv) Is the member function OUTPUT() accessible by the objects of the class Country ?
Answer:
(i) The base class of Country is World, and its derived class is State.
(ii) Inside the DISPLAY() function, the accessible data members are M and U.
(iii) The member functions accessible from objects of class State are DISPLAY(), INDATA(), and OUTDATA().
(iv) No, because Country inherits from World privately, which hides the public function OUTPUT() from external objects.
In simple words: Private inheritance blocks any further propagation of access to the base class's public methods for external objects and future derived classes.
Exam Tip: When a class inherits privately, its child classes cannot access the protected members of the grandparent class.
Question. Answer the questions (i) to (v) based on the following code :
class Employee
{
int id;
protected:
char name[20];
char doj[20];
public :
Employee( );
~Employee( );
void get( );
void show( );
};
class Daily_wager : protected Employee
{
int wphour;
protected :
int nofhworked;
public :
void getd( );
void showd( );
};
class Payment : private Daily_wager
{
char date[10];
protected :
int amount;
public :
Payment( );
~Payment( );
void show( );
};
(i) Name the member functions, which are accessible by the objects of class Payment.
(ii) From the following, Identify the member function(s) that can be called directly from the object of class Daily_wager class show( ), getd( ), get( )
(iii) Find the memory size of object of class Daily_wager.
(iv) Is the constructors of class Employee will copied in class Payment Due to Inheritance?
Answer:
(i) The only member function accessible from objects of class Payment is its own public function show().
(ii) From the list, only getd() can be called directly from an object of class Daily_wager.
(iii) An object of class Daily_wager requires 46 bytes of memory.
(iv) No, constructors are not inherited or copied into derived classes under inheritance.
In simple words: Constructors cannot be inherited by child classes. Each class must have its own constructor to initialize its specific members.
Exam Tip: Remember that constructors, destructors, and overloaded assignment operators are never inherited by derived classes.
Question. Answer the questions (i) to (iii) based on the following code:
class toys
{
char Code;
char Manufacturer [10];
public:
toys( );
void Read_toy_details ( );
void Disp_toy_details( );
};
class electronic : public toys
{
int no_of_types;
float cost_of_toy;
public:
void Read_elect_details ( );
void Disp_elect_details ( );
};
class infants : private electronic
{
int no_of_buyers;
char delivery_date[10];
public:
void Read_infant_details ( );
void Disp_infant_details( );
};
void main ( )
{
infants MyToy;
}
(a) Mention the member names which are accessible by MyToy declared in main ( ) function.
(b) What is the size of MyToy in bytes?
(c) Mention the names of functions accessible from the member function Read_infant_details () of class printer.
(d) Which type of inheritance shown in the above code?
Answer:
(a) The member functions accessible by MyToy in main() are Read_infant_details() and Disp_infant_details().
(b) The size of MyToy is 29 bytes.
(c) The functions accessible from Read_infant_details() are Disp_infant_details(), Read_elect_details(), Disp_elect_details(), Read_toy_details(), and Disp_toy_details().
(d) The type of inheritance shown is multilevel inheritance.
In simple words: Multilevel inheritance creates a chain where each class inherits from the previous one. Private inheritance at the end of the chain cuts off external access to grandparent methods.
Exam Tip: Be careful with memory calculations; a single char occupies 1 byte, while an array of char[10] occupies 10 bytes.
Free study material for Computer Science
HOTS for Programming in C++ Computer Science Class 12
Students can now practice Higher Order Thinking Skills (HOTS) questions for Programming in C++ to prepare for their upcoming school exams. This study material follows the latest syllabus for Class 12 Computer Science released by CBSE. These solved questions will help you to understand about each topic and also answer difficult questions in your Computer Science test.
NCERT Based Analytical Questions for Programming in C++
Our expert teachers have created these Computer Science HOTS by referring to the official NCERT book for Class 12. These solved exercises are great for students who want to become experts in all important topics of the chapter. After attempting these challenging questions should also check their work with our teacher prepared solutions. For a complete understanding, you can also refer to our NCERT solutions for Class 12 Computer Science available on our website.
Master Computer Science for Better Marks
Regular practice of Class 12 HOTS will give you a stronger understanding of all concepts and also help you get more marks in your exams. We have also provided a variety of MCQ questions within these sets to help you easily cover all parts of the chapter. After solving these you should try our online Computer Science MCQ Test to check your speed. All the study resources on studiestoday.com are free and updated for the current academic year.
FAQs
You can download the teacher-verified PDF for CBSE Class 12 Computer Science HOTs Programming in C++ from StudiesToday.com. These questions have been prepared for Class 12 Computer Science to help students learn high-level application and analytical skills required for the 2026-27 exams.
In the 2026 pattern, 50% of the marks are for competency-based questions. Our CBSE Class 12 Computer Science HOTs Programming in C++ are to apply basic theory to real-world to help Class 12 students to solve case studies and assertion-reasoning questions in Computer Science.
Unlike direct questions that test memory, CBSE Class 12 Computer Science HOTs Programming in C++ require out-of-the-box thinking as Class 12 Computer Science HOTS questions focus on understanding data and identifying logical errors.
After reading all conceots in Computer Science, practice CBSE Class 12 Computer Science HOTs Programming in C++ by breaking down the problem into smaller logical steps.
Yes, we provide detailed, step-by-step solutions for CBSE Class 12 Computer Science HOTs Programming in C++. These solutions highlight the analytical reasoning and logical steps to help students prepare as per CBSE marking scheme.