30 Question Practise Set For C
30 Question Practise Set For C
C++:
USE COMMENTS IN EVERY
SET OF CODE
Section A – Short Answer (2 Marks Each)
1. Define a class in C++. How does it differ
from a structure?
2. What is an object in C++? Give a real-life
example.
3. Write the output:
int x = 5, y = 7;
cout << (x > y ? x : y);
4. What is the difference between member
functions defined inside and outside a
class?
5. Explain functions in C++ with a simple
example.
6. What is the purpose of private member
functions in a class?
7. Write the output:
char str[] = "HELLO";
cout << str[1] << str[4];
8. Define a friend function. Why is it
required?
9. What is meant by array of objects? Give
an example.
10. State the difference between constructor
and destructor.
And cannot be
Modifier
changed
Limited
Supports full
encapsulation
Encapsulati encapsulation
(by default
on (data hiding
everything is
possible)
public)
commonly
used
When
When only
abstraction, data
grouping of
Use Case hiding, or OOP
data is needed
features are
(like records)
needed
In short: (For 2 marks answer )
Structure is data-centric (good for
grouping raw data).
Class is powerful, object-oriented,
supports full encapsulation, abstraction,
inheritance, polymorphism.
Code for :
1. Class:
class ClassName {
private:
int data;
public:
void setData(int x) { data = x; }
int getData() { return data; } };
2. Structure
#include <iostream>
using namespace std;
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
Student s1;
s1.rollNo = 101;
strcpy(s1.name, "Arpit");
s1.marks = 89.5;
cout << "Roll No: " << s1.rollNo <<
endl;
cout << "Name: " << s1.name <<
endl;
cout << "Marks: " << s1.marks <<
endl;
return 0;
}
Q 2)
Sol.
An object in C++ is a real-world entity
created from a class.
A class is like a blueprint or template.
An object is like the actual thing built
from that blueprint.
(If for 5-6 marks)
class Car {
public:
string brand;
int speed;
void drive() {
cout << brand << " is driving at " <<
speed << " km/h" << endl;
}
};
int main() {
Car obj1; // object created from
class Car
obj1.brand = "BMW";
obj1.speed = 120;
obj1.drive();
return 0;
}
Real life example :
Let an Mobile Phones 📱:
Class → "Mobile" (
blueprint: defines what features a mobile
has like brand, RAM, camera, etc.
Objects → Specific mobiles:
o Mobile m1 = Samsung Galaxy S23
o Mobile m2 = iPhone 14
Both are created from the same class
Mobile, but have different object
properties (brand, price, features).
Q 3)
Sol.
(x > y ? x : y)
Breakdown of code:
Condition ? if true : if false
So, sol here is:
x=5
y=7
Condition: x > y → 5 > 7 → false
Therefore, answer is second condition
Quick practice:
i.)
int a = 10, b = 20;
cout << (a < b ? a : b);
ii.)
int x = 15, y = 15;
cout << (x == y ? x + y : x - y);
iii.)
int a = 5, b = 10, c = 15;
cout << (a > b ? (a > c ? a : c) : (b > c ? b :
c));
Q 4)(mention code for 6 marks )
Sol.
A member function is a function that is
defined inside a class and operates on the
data members of that class.
Key Differences
Feature Inside Class Outside Class
Defined directly Declared inside
Definition
inside class class, defined
Place
body outside using ::
Treated as
Default Not inline by
inline (unless
Nature default
too complex)
Suitable for Suitable for
Use Case small/simple large/complex
functions functions
Readabili Can make class Keeps class
Feature Inside Class Outside Class
bulky if too definition neat
ty
many functions and organized
1. Inside the Class
Defined directly in the class body.
Automatically treated as inline
(compiler may expand them inline).
Best for small/simple functions.
👉 Example:
class Student {
public:
int marks;
void display();
};
int main() {
greet(); // function call
return 0;
}
Output:
Hello! Welcome to C++
2. Parameterized Function
Function takes parameters (arguments)
but may or may not return a value.
👉 Example (with parameter, no return):
#include <iostream>
using namespace std;
int main() {
square(5);
return 0;
}
Output:
Square = 25
3. Void Function
Function explicitly defined as void.
Can take parameters but cannot return
a value.
👉 Example:
#include <iostream>
using namespace std;
int main() {
displaySum(10, 20);
return 0;
}
Output:
Sum = 30
int main() {
int result = add(7, 8);
cout << "Result = " << result << endl;
return 0;
}
Output:
Result = 15
Q 6)
Sol.
2 marker sol
Private Member Functions in C++
By default, class members can be
private, protected, or public.
A private member function is a
function inside a class that:
o Cannot be accessed directly from
outside the class.
o Can only be called by other
member functions of the same
class.
5-6 marker
Purpose of Private Member Functions
1. Data Hiding & Security
o Prevents direct access to sensitive
logic from outside the class.
o Ensures only trusted (public)
functions can control it.
2. Helper/Utility Functions
o Used internally by the class to
support public functions.
o Keeps implementation details hidden
from the user.
3. Encapsulation
o Enforces the OOP principle of
wrapping data + related functions
together, exposing only what’s
necessary.
4. Clean Interface
o Users interact only with public
methods (the “what”), not with
internal helper functions (the “how”).
Example
#include <iostream>
using namespace std;
class BankAccount {
private:
int balance;
public:
BankAccount(int b) { balance = b; }
void showBalance() {
cout << "Current Balance = " <<
balance << endl;
}
};
int main() {
BankAccount acc(1000);
acc.deposit(500); // Allowed (public)
acc.showBalance(); // Allowed (public)
return 0;
}
Output
Transaction of 500 processed.
Current Balance = 1500
Q 8)
Sol.
2 marker:
A friend function in C++ is a special
function that is not a member of a class
but has the right to access its private
and protected members.
Why is it Required? (Purpose)(atmost 2
points )
1. Access to Private/Protected Data
o Normally, private/protected members
can’t be accessed outside the class.
o A friend function is an exception — it
can directly access them.
2. Operator Overloading
o Many times, when we overload
operators (like +, ==), we need
access to private data from outside.
3. Flexibility
o Sometimes, two or more classes
need to share each other’s private
data.
o Friend functions make this sharing
possible without making everything
public.
4. Non-Member Utility Functions
o Some functions are logically related
to a class but should not be its
members.
o They can still access private data if
declared as friend.
6 marker
Definition of Friend Function
A friend function in C++ is a special
function that is not a member of a class
but has the right to access its private
and protected members.
👉 Declared using the keyword friend inside
the class.
Syntax
class ClassName {
private:
int data;
public:
friend void showData(ClassName obj); //
declaration of friend function
};
Example
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box(int l) { length = l; }
Output
Length of box = 10
Key Points
Friend function is not a member, but
has special access.
Declared inside the class using friend.
Defined normally like any other function
(outside class).
Can access private and protected
members.
Q 9)
Sol.
No code required for 2 marker
Array of Objects in C++
An array of objects means we create
multiple objects of the same class,
stored in a single array (like we store
multiple integers in an int array).
Useful jab ek hi class ke bahut saare
records store karne ho (jaise students,
employees, books).
Syntax
ClassName objName[array_size];
class Student {
private:
int roll;
string name;
public:
void input() {
cout << "Enter Roll No: ";
cin >> roll;
cout << "Enter Name: ";
cin >> name;
}
void display() {
cout << "Roll: " << roll << ", Name: "
<< name << endl;
}
};
int main() {
Student s[3]; // array of 3 Student
objects
return 0;
}
Sample Input
Student 1:
Enter Roll No: 101
Enter Name: Arpit
Student 2:
Enter Roll No: 102
Enter Name: Neha
Student 3:
Enter Roll No: 103
Enter Name: Raj
Output
--- Student Records ---
Roll: 101, Name: Arpit
Roll: 102, Name: Neha
Roll: 103, Name: Raj
Q 10)
Sol.
Constructor vs Destructor in C++
Feature Constructor Destructor
Used to
Used to clean up
Purpose initialize
(destroy) objects
objects
Same as class
Same as class
Name name but
name
preceded by ~
Can take Cannot take
Paramete
parameters parameters (no
rs
(overloaded) overloading)
Return No return type
No return type
type (not even void)
Call Time Called Called
Feature Constructor Destructor
automatically
automatically
when object goes
when object is
out of scope /
created
program ends
Cannot be
Overloadi Can be overloaded (only
ng overloaded one destructor
per class)
Multiple Only one
Count in
constructors destructor
Class
allowed allowed
class Student {
private:
string name;
int rollNo;
float marks;
public:
// Function to input details
void input() {
cout << "Enter Name: ";
cin >> name;
cout << "Enter Roll No: ";
cin >> rollNo;
cout << "Enter Marks: ";
cin >> marks;
}
int main() {
Student s1; // object created
return 0;
}
Sample Input
Enter Name: Arpit
Enter Roll No: 101
Enter Marks: 89.5
Output
--- Student Details ---
Name: Arpit
Roll No: 101
Marks: 89.5
Q 12)
Sol.
Function Overloading in C++
👉 Definition:
Function Overloading means using the
same function name with different
parameter lists (different number or type
of arguments).
Compiler decides which function to call
based on the arguments passed.
Return type alone cannot differentiate
overloaded functions.
class Shape {
public:
// Function to calculate area of a square
int area(int side) {
return side * side;
}
int main() {
Shape s;
int side = 5;
int length = 10, breadth = 6;
return 0;
}
Output
Area of Square (side = 5) = 25
Area of Rectangle (10 x 6) = 60
Key Points
Same function name → area()
Different parameters → one takes 1
int, the other takes 2 int.
Compiler automatically decides which
one to call (compile-time
polymorphism).
Q 13)
Code:
#include <iostream>
#include <string>
using namespace std;
class StringAdder {
public:
// Function to add (concatenate) two
strings
string addStrings(string s1, string s2) {
return s1 + s2; // + operator joins two
strings
}
};
int main() {
StringAdder obj;
string str1, str2;
return 0;
}
Sample Input:
Enter first string: Hello
Enter second string: World
Output:
Concatenated String = HelloWorl
Q 14
Sol.
What is Nesting of Member Functions?
👉 Definition:
When one member function of a class
calls another member function of the
same class, it is called nesting of
member functions.
Helps to reuse code within the same
class.
Reduces duplication and keeps program
modular.
class Student {
private:
int marks;
// Private function
char getGrade() {
if (marks >= 90) return 'A';
else if (marks >= 75) return 'B';
else if (marks >= 50) return 'C';
else return 'F';
}
public:
void input() {
cout << "Enter Marks: ";
cin >> marks;
}
void display() {
cout << "Marks = " << marks <<
endl;
cout << "Grade = " << getGrade() <<
endl; // nested function call
}
};
int main() {
Student s;
s.input();
s.display(); // display() internally calls
getGrade()
return 0;
}
Sample Input
Enter Marks: 82
Output
Marks = 82
Grade = B
Explanation
display() is a public function.
Inside display(), we call another function
getGrade() (which is private).
This is nesting of member functions.
Q 15 )
Sol
#include <iostream>
using namespace std;
class Employee {
private:
int id;
float salary;
public:
// Function to input details
void input() {
cout << "Enter Employee ID: ";
cin >> id;
cout << "Enter Salary: ";
cin >> salary;
}
int main() {
Employee emp[5]; // Array of 5
Employee objects
public:
A(int x) { numA = x; }
class B {
private:
int numB;
public:
B(int y) { numB = y; }
int main() {
A obj1(25);
B obj2(40);
return 0;
}
Output
ini
Copy code
Maximum = 40
Explanation
Classes A and B have private data members
(numA and numB).
int main() {
Calculator c;
return 0;
}
Output
Sum with one argument (10): 15
Sum with two arguments (10, 20): 30
Explanation:
Function add(int a, int b = 5) → here b has a
default value of 5.
class Student {
private:
string name;
int rollNo;
public:
// Default constructor
Student() {
name = "Unknown";
rollNo = 0;
}
void display() {
cout << "Name: " << name << ", Roll
No: " << rollNo << endl;
}
};
int main() {
Student s1; // Default constructor called
s1.display();
return 0;
}
Output
Name: Unknown, Roll No: 0
class Student {
private:
string name;
int rollNo;
public:
// Parameterized constructor
Student(string n, int r) {
name = n;
rollNo = r;
}
void display() {
cout << "Name: " << name << ", Roll
No: " << rollNo << endl;
}
};
int main() {
Student s1("Arpit", 101); //
Parameterized constructor called
Student s2("Raj", 102);
s1.display();
s2.display();
return 0;
}
Output
Name: Arpit, Roll No: 101
Name: Raj, Roll No: 102
Q 19)
Sol.
Copy Constructor in C++
Definition: A copy constructor is a
special constructor used to initialize a
new object as a copy of an existing
object.
Syntax:
ClassName (const ClassName &obj) {
Codes
}
Program Example
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
public:
// Parameterized constructor
Student(string n, int r) {
name = n;
rollNo = r;
}
// Copy constructor
Student(const Student &s) {
name = s.name;
rollNo = s.rollNo;
}
void display() {
cout << "Name: " << name << ", Roll
No: " << rollNo << endl;
}
};
int main() {
Student s1("Arpit", 101); //
Parameterized constructor
Student s2 = s1; // Copy
constructor called
return 0;
}
Output
Details of original object:
Name: Arpit, Roll No: 101
Details of copied object:
Name: Arpit, Roll No: 101
Explanation
1. s1 is created using parameterized
constructor.
2. s2 is created as a copy of s1 →
triggers copy constructor.
3. Copy constructor copies all data
members of s1 to s2.
Q 20)
Sol.
Dynamic Initialization of Objects in C++
Dynamic Initialization means
initializing objects at the time of
creation using constructor
parameters.
Achieved using parameterized
constructors.
Example Program
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
float marks;
public:
// Parameterized constructor (dynamic
initialization)
Student(string n, int r, float m) {
name = n;
rollNo = r;
marks = m;
}
void display() {
cout << "Name: " << name << ", Roll
No: " << rollNo
<< ", Marks: " << marks << endl;
}
};
int main() {
// Dynamic initialization at the time of
object creation
Student s1("Arpit", 101, 89.5);
Student s2("Neha", 102, 92.0);
return 0;
}
Output
--- Student Details ---
Name: Arpit, Roll No: 101, Marks: 89.5
Name: Neha, Roll No: 102, Marks: 92
Explanation
1. Parameterized constructor allows
passing values when creating an object.
2. Student s1("Arpit", 101, 89.5); →
dynamically initializes s1 with these
values.
3. Each object can be initialized with
different values at runtime.
Q 21)
Sol.
#include <iostream>
using namespace std;
class BankAccount {
private:
float balance;
public:
// Default constructor to initialize balance
BankAccount() {
balance = 1000; // initial balance
}
// Function to deposit money
void deposit(float amount) {
balance += amount;
cout << "Amount deposited: " <<
amount << endl;
}
int main() {
BankAccount acc; // default constructor
called
class Book {
private:
string title;
string author;
float price;
public:
// Function to input book details
void input() {
cout << "Enter Book Title: ";
cin >> ws; // to consume any leftover
newline
getline(cin, title);
cout << "Enter Author Name: ";
getline(cin, author);
cout << "Enter Price: ";
cin >> price;
}
int main() {
Book books[3]; // array of 3 Book objects
return 0;
}
Sample Input
yaml
Copy code
Book 1:
Enter Book Title: C++Basics
Enter Author Name: Arpit
Enter Price: 250
Book 2:
Enter Book Title: DataStructures
Enter Author Name: Neha
Enter Price: 300
Book 3:
Enter Book Title: Algorithms
Enter Author Name: Raj
Enter Price: 350
Sample Output
makefile
Copy code
--- Book Details ---
Title: C++Basics
Author: Arpit
Price: 250
Title: DataStructures
Author: Neha
Price: 300
Title: Algorithms
Author: Raj
Price: 350
Q 24)
Sol.
#include <iostream>
using namespace std;
class Student {
private:
string name;
int rollNo;
float marks;
public:
// Constructor 1: No arguments (default
constructor)
Student() {
name = "Unknown";
rollNo = 0;
marks = 0;
}
void display() {
cout << "Name: " << name << ", Roll
No: " << rollNo
<< ", Marks: " << marks << endl;
}
};
int main() {
// Using different constructors
Student s1; // default
constructor
Student s2("Arpit"); //
constructor with 1 argument
Student s3("Neha", 102, 95.5); //
constructor with 3 arguments
return 0;
}
Output
yaml
Copy code
--- Student Details ---
Name: Unknown, Roll No: 0, Marks: 0
Name: Arpit, Roll No: 0, Marks: 0
Name: Neha, Roll No: 102, Marks: 95.5
Q 25)
Sol.
#include <iostream>
using namespace std;
class Demo {
public:
// Constructor
Demo() {
cout << "Constructor called: Object
created" << endl;
}
// Destructor
~Demo() {
cout << "Destructor called: Object
destroyed" << endl;
}
};
int main() {
cout << "Inside main function" << endl;
Demo obj1; // Constructor called here
{
Demo obj2; // Constructor called for
obj2
cout << "Inside inner block" << endl;
} // obj2 goes out of scope here →
Destructor automatically called
return 0;
} // obj1 goes out of scope here →
Destructor automatically called
Output
pgsql
Copy code
Inside main function
Constructor called: Object created
Constructor called: Object created
Inside inner block
Destructor called: Object destroyed
Back to main function
Destructor called: Object destroyed
Q 26)
Sol.
ChatGPT said:
Bhai, ye object memory allocation ka
question hai, simple aur clear tarike se
samjhate hain.
class Demo {
private:
int value;
public:
Demo() { value = 0; cout <<
"Constructor called" << endl; }
void setValue(int v) { value = v; }
void display() { cout << "Value = " <<
value << endl; }
};
int main() {
Demo obj1, obj2; // Static allocation
(stack memory)
obj1.setValue(10);
obj2.setValue(20);
obj1.display();
obj2.display();
return 0;
}
Output
Constructor called
Constructor called
Value = 10
Value = 20
class Demo {
private:
int value;
public:
Demo() { value = 0; cout <<
"Constructor called" << endl; }
void setValue(int v) { value = v; }
void display() { cout << "Value = " <<
value << endl; }
};
int main() {
Demo *obj1 = new Demo; // Dynamic
allocation (heap)
Demo *obj2 = new Demo;
obj1->setValue(30);
obj2->setValue(40);
obj1->display();
obj2->display();
return 0;
}
Output
Constructor called
Constructor called
Value = 30
Value = 40
Summary
How
Type Memory Lifetime Example
Allocated
Static Stack Until Demo obj;
How
Type Memory Lifetime Example
Allocated
scope
ends
Until Demo *obj
Dynami
Heap delete is = new
c
called Demo;
Q 27)
Sol.)
Program: Friend Function to Sum
Private Members of Two Classes
#include <iostream>
using namespace std;
class A {
private:
int numA;
public:
void setValue(int x) { numA = x; }
class B {
private:
int numB;
public:
void setValue(int y) { numB = y; }
int main() {
A obj1;
B obj2;
obj1.setValue(15);
obj2.setValue(25);
return 0;
}
Output
Sum = 40
Q 28)
Sol.
ChatGPT said:
Bhai, ye function template ka classic
example hai. Chalo ekdum simple aur
exam-ready code bana dete hain:
// Function template
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int i1 = 10, i2 = 20;
float f1 = 12.5, f2 = 9.8;
char c1 = 'A', c2 = 'Z';
cout << "Maximum of " << i1 << " and "
<< i2 << " = " << findMax(i1, i2) << endl;
cout << "Maximum of " << f1 << " and "
<< f2 << " = " << findMax(f1, f2) << endl;
cout << "Maximum of " << c1 << " and "
<< c2 << " = " << findMax(c1, c2) <<
endl;
return 0;
}
Output
Maximum of 10 and 20 = 20
Maximum of 12.5 and 9.8 = 12.5
Maximum of A and Z = Z
Q 29 )
Sol.
Do it yourself already taught
Q 30 )
Sol.
ChatGPT said:
Bhai, ye question function templates ka
classic example hai. Chalo ekdum clean
program bana dete hain:
// Function template
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int x = 10, y = 20;
float p = 12.5, q = 9.8;
char c1 = 'A', c2 = 'Z';
cout << "Maximum of " << x << " and "
<< y << " = " << findMax(x, y) << endl;
cout << "Maximum of " << p << " and "
<< q << " = " << findMax(p, q) << endl;
cout << "Maximum of " << c1 << " and "
<< c2 << " = " << findMax(c1, c2) <<
endl;
return 0;
}
Output
Maximum of 10 and 20 = 20
Maximum of 12.5 and 9.8 = 12.5
Maximum of A and Z = Z