0% found this document useful (0 votes)
8 views86 pages

30 Question Practise Set For C

Uploaded by

utkg1696
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views86 pages

30 Question Practise Set For C

Uploaded by

utkg1696
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

30 question practise set for

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.

Section B – Descriptive (6 Marks Each)


11. Write a program to create a class
Student with data members name, rollNo,
and
marks. Write member functions to input and
display the details.
12. Explain function overloading with a
program that finds the area of a square and
rectangle.
13. Write a program to add two strings using
a function.
14. Demonstrate the use of nesting of
member functions in C++ with an example.
15. Write a program to implement an array
of objects for a class Employee storing ID
and salary of 5 employees.
16. Write a program to illustrate the concept
of friend function by finding the maximum
of two numbers from two different classes.

17. Write a program that demonstrates


default arguments in a member function.
18. Differentiate between default
constructor and parameterized constructor
with
examples.
19. Write a program to demonstrate copy
constructor in C++.
20. Explain with code how dynamic
initialization of objects works using
constructors.

Section C – Long Answer / Application (10


Marks Each)
21. Write a program for a class BankAccount
that has functions to deposit, withdraw,
and display balance. Implement a default
constructor to initialize balance = 1000.
22. Write a program to create a class
Complex with real and imaginary parts.
Overload
the + function to add two complex numbers.
23. Write a program to create a class Book
with data members for title, author, and
price. Demonstrate an array of objects to
input and display details of 3 books.
24. Write a program to illustrate constructor
overloading with at least three
constructors.
25. Write a program to demonstrate
destructor being called automatically when
objects
go out of scope.
26. Explain memory allocation for objects in
C++. Show with a small program using
multiple objects.
27. Write a program using friend function to
calculate the sum of two private data
members from two different classes.
28. Write a program that implements a
function template to find the maximum of
two
values (int, float, char).
29. WAP to swap two number and calculate
the factorial of given program.
30. Write a program to demonstrate
constructor with default arguments to
calculate
simple interest.
SOLUTIONS with QUESTION NUMBER
Q1.
Sol)
Difference between Class and Structure
in C++

Feature Class Structure

Default Always private Always public


Access
Feature Class Structure

And cannot be
Modifier
changed

Limited
Supports full
encapsulation
Encapsulati encapsulation
(by default
on (data hiding
everything is
possible)
public)

Can also have


Can have both
both (but
Member data members
traditionally
Functions and member
used only for
functions
data)

Inheritance Supports Supports


inheritance inheritance too
(since C++),
but not
Feature Class Structure

commonly
used

Designed mainly Designed


Object- for OOP mainly for
Oriented (encapsulation, grouping data
Concept inheritance, (like C-style
polymorphism) structs)

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;

// Function defined inside class


void display() {
cout << "Marks = " << marks <<
endl;
}
};

2. Outside the Class


 Function prototype (declaration) is inside
the class.
 Actual definition is written outside using
scope resolution operator (::).
 Better for large/complex functions to
keep class definition clean.
👉 Example:
class Student {
public:
int marks;

void display();
};

// Function defined outside the class


void Student::display() {
cout << "Marks = " << marks << endl;
}
Q 5)
Sol.)
Tabled one for 2 marks :
Quick Recap Table
Paramete Return Example
Type
rs? Value? Use
Just print a
Default ❌ No ❌ No
message
❌ Perform
Parameteri
✅ Yes Optiona task with
zed
l input
Display
Void ✅/❌ ❌ No result
directly
Return a
Valued ✅/❌ ✅ Yes computed
value
--------------------------------------------------------------
----
For 5-6 marker
There are 4 types of Function :
1. Default (No parameters, No return
value)
 Function neither takes input nor returns
output.
 Just performs a task.
👉 Example:
#include <iostream>
using namespace std;

void greet() { // no parameters, no return


cout << "Hello! Welcome to C++" <<
endl;
}

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;

void square(int n) { // takes parameter, no


return
cout << "Square = " << n * n << endl;
}

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;

void displaySum(int a, int b) { // void return


type
cout << "Sum = " << a + b << endl;
}

int main() {
displaySum(10, 20);
return 0;
}
Output:
Sum = 30

4. Valued Function (int, double, float,


etc.)
 Function returns a value of some type
(like int, double, float).
 Caller can store the returned result.
👉 Example:
#include <iostream>
using namespace std;

int add(int a, int b) { // returns int


return a + b;
}

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;

// Private function (helper function)


void logTransaction(int amount) {
cout << "Transaction of " << amount
<< " processed." << endl;
}

public:
BankAccount(int b) { balance = b; }

void deposit(int amount) {


balance += amount;
logTransaction(amount); // private
function used here
}

void showBalance() {
cout << "Current Balance = " <<
balance << endl;
}
};

int main() {
BankAccount acc(1000);
acc.deposit(500); // Allowed (public)
acc.showBalance(); // Allowed (public)

// acc.logTransaction(500); Error: private


function not accessible

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
};

Why is it Required? (Purpose)


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.

Example
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box(int l) { length = l; }

// Friend function declaration


friend void printLength(Box b);
};

// Friend function definition


void printLength(Box b) {
cout << "Length of box = " << b.length
<< endl; // accessing private member
}
int main() {
Box b1(10);
printLength(b1); // allowed due to friend
return 0;
}

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];

Example: Array of Student Objects


#include <iostream>
using namespace std;

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

cout << "--- Enter Student Details ---\n";


for (int i = 0; i < 3; i++) {
cout << "Student " << i + 1 << ":\n";
s[i].input(); // input for each object
}

cout << "\n--- Student Records ---\n";


for (int i = 0; i < 3; i++) {
s[i].display(); // display each object
}

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

Only descriptive ones (6 markers)


Q 11
Sol.
#include <iostream>
using namespace std;

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;
}

// Function to display details


void display() {
cout << "\n--- Student Details ---" <<
endl;
cout << "Name: " << name << endl;
cout << "Roll No: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
Student s1; // object created

s1.input(); // input details


s1.display(); // display details

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.

Program: Area of Square and Rectangle


using Function Overloading
#include <iostream>
using namespace std;

class Shape {
public:
// Function to calculate area of a square
int area(int side) {
return side * side;
}

// Function to calculate area of a rectangle


int area(int length, int breadth) {
return length * breadth;
}
};

int main() {
Shape s;

int side = 5;
int length = 10, breadth = 6;

cout << "Area of Square (side = " <<


side << ") = " << s.area(side) << endl;
cout << "Area of Rectangle (" << length
<< " x " << breadth << ") = "
<< s.area(length, breadth) << endl;

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;

cout << "Enter first string: ";


cin >> str1;
cout << "Enter second string: ";
cin >> str2;

string result = obj.addStrings(str1, str2);

cout << "Concatenated String = " <<


result << endl;

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.

Example: Nesting of Member Functions


#include <iostream>
using namespace std;

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;
}

// Function to display details


void display() {
cout << "ID: " << id << ", Salary: " <<
salary << endl;
}
};

int main() {
Employee emp[5]; // Array of 5
Employee objects

cout << "--- Enter details of 5 employees


---\n";
for (int i = 0; i < 5; i++) {
cout << "\nEmployee " << i + 1 << ":\
n";
emp[i].input();
}

cout << "\n--- Employee Details ---\n";


for (int i = 0; i < 5; i++) {
emp[i].display();
}
return 0;
}
Sample Input:
Employee 1:
Enter Employee ID: 101
Enter Salary: 25000
Employee 2:
Enter Employee ID: 102
Enter Salary: 30000
Output:
--- Employee Details ---
ID: 101, Salary: 25000
ID: 102, Salary: 30000
Q 16)
Sol.
#include <iostream>
using namespace std;

class B; // Forward declaration


class A {
private:
int numA;

public:
A(int x) { numA = x; }

// Declare friend function


friend int findMax(A obj1, B obj2);
};

class B {
private:
int numB;

public:
B(int y) { numB = y; }

// Declare friend function


friend int findMax(A obj1, B obj2);
};

// Friend function definition


int findMax(A obj1, B obj2) {
if (obj1.numA > obj2.numB)
return obj1.numA;
else
return obj2.numB;
}

int main() {
A obj1(25);
B obj2(40);

cout << "Maximum = " << findMax(obj1,


obj2) << endl;

return 0;
}
Output
ini
Copy code
Maximum = 40
Explanation
Classes A and B have private data members
(numA and numB).

Normally, ek dusre ka private data access


nahi kar sakte.

Friend function findMax() is declared inside


both classes → so it can access their private
members.

Function compares numbers and returns the


maximum.
Q 17)
Sol.
#include <iostream>
using namespace std;
class Calculator {
public:
// Function with default arguments
int add(int a, int b = 5) {
return a + b;
}
};

int main() {
Calculator c;

cout << "Sum with one argument (10): "


<< c.add(10) << endl; // b = 5 by
default
cout << "Sum with two arguments (10,
20): " << c.add(10, 20) << endl; // b = 20
given

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.

If we call c.add(10) → a = 10, b takes


**default value = 5`.

If we call c.add(10, 20) → a = 10, b = 20


(overrides default).
Q 18)
Sol.
Difference: Default vs Parameterized
Constructor
Default Parameterized
Feature
Constructor Constructor
Definiti A constructor A constructor that
on that does not takes one or
Default Parameterized
Feature
Constructor Constructor
take any more
arguments. arguments.
Initializes Initializes objects
Purpos objects with with specific
e fixed / default values given by
values. user.
ClassName(type
ClassName()
Syntax arg1, type
{ ... }
arg2, ...) { ... }
Called
Called
automatically
automatically
when object is
Call when object is
created
created with
without
parameters.
parameters.

Example: Default Constructor


#include <iostream>
using namespace std;

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

Example: Parameterized Constructor


#include <iostream>
using namespace std;

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

cout << "Details of original object:" <<


endl;
s1.display();

cout << "Details of copied object:" <<


endl;
s2.display();

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);

cout << "--- Student Details ---" << endl;


s1.display();
s2.display();

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;
}

// Function to withdraw money


void withdraw(float amount) {
if (amount > balance) {
cout << "Insufficient balance!" <<
endl;
} else {
balance -= amount;
cout << "Amount withdrawn: " <<
amount << endl;
}
}

// Function to display balance


void displayBalance() {
cout << "Current balance: " <<
balance << endl;
}
};

int main() {
BankAccount acc; // default constructor
called

acc.displayBalance(); // show initial


balance

acc.deposit(500); // deposit 500


acc.displayBalance();

acc.withdraw(200); // withdraw 200


acc.displayBalance();

acc.withdraw(2000); // try to withdraw


more than balance
return 0;
}
Sample Output
Current balance: 1000
Amount deposited: 500
Current balance: 1500
Amount withdrawn: 200
Current balance: 1300
Insufficient balance!
Q 23)
Sol.
Code:
#include <iostream>
using namespace std;

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;
}

// Function to display book details


void display() {
cout << "\nTitle: " << title
<< "\nAuthor: " << author
<< "\nPrice: " << price << endl;
}
};

int main() {
Book books[3]; // array of 3 Book objects

cout << "--- Enter details of 3 books ---\


n";
for (int i = 0; i < 3; i++) {
cout << "\nBook " << i + 1 << ":\n";
books[i].input();
}

cout << "\n--- Book Details ---\n";


for (int i = 0; i < 3; i++) {
books[i].display();
}

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;
}

// Constructor 2: One argument


Student(string n) {
name = n;
rollNo = 0;
marks = 0;
}
// Constructor 3: Three arguments
(parameterized)
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() {
// Using different constructors
Student s1; // default
constructor
Student s2("Arpit"); //
constructor with 1 argument
Student s3("Neha", 102, 95.5); //
constructor with 3 arguments

cout << "--- Student Details ---" << endl;


s1.display();
s2.display();
s3.display();

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

cout << "Back to main function" << endl;

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.

Memory Allocation for Objects in C++


1. Static (Compile-time) Allocation:
o Jab object ko directly declare kiya
jata hai.
o Memory stack par allocate hoti hai.
o Example: ClassName obj;
2. Dynamic (Run-time) Allocation:
o Jab object ko new keyword ke
through create kiya jata hai.
o Memory heap par allocate hoti hai.
o Example: ClassName *obj = new
ClassName;
o Destructor automatically tabhi call
nahi hota, manually delete obj;
karna padta hai.

Program: Multiple Objects (Static


Allocation)
#include <iostream>
using namespace std;

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

Program: Dynamic Allocation Using


new
#include <iostream>
using namespace std;

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();

delete obj1; // Free heap memory


delete obj2;

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 B; // Forward declaration

class A {
private:
int numA;
public:
void setValue(int x) { numA = x; }

// Declare friend function


friend int sum(A a, B b);
};

class B {
private:
int numB;

public:
void setValue(int y) { numB = y; }

// Declare friend function


friend int sum(A a, B b);
};

// Friend function definition


int sum(A a, B b) {
return a.numA + b.numB; // Access
private members of both classes
}

int main() {
A obj1;
B obj2;

obj1.setValue(15);
obj2.setValue(25);

cout << "Sum = " << sum(obj1, obj2)


<< endl;

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:

Program: Function Template to Find


Maximum
#include <iostream>
using namespace std;

// 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:

Program: Function Template to Find


Maximum
#include <iostream>
using namespace std;

// 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

You might also like