C++ Programming
Complete Question Solutions with Explanations
■ All 6 questions solved step-by-step | Concepts: Default Arguments, OOP, Classes, Friend Functions,
Constructors
Topics Covered:
• Q1 – Default Arguments | Compound Interest Formula
• Q2 – Operator Overloading / Object Passing | Land Measurement (Ropani-Ana-Paisa-Dam)
• Q3 – OOP: Distance Between Two Points
• Q4 – Friend Functions | Unit Conversion (Metric ↔ Imperial)
• Q5 – Classes with Setter/Getter | Carport Parking Charges
• Q6 – Constructors with Logic | Person Class with Citizenship
Question 1: Compound Interest – Default Argument
■ Concept: Default Arguments
In C++, a function parameter can have a default value. If the caller does not pass that argument, the
default is used automatically. Here, the interest rate r has a default value of 50.
■ Formula
A = P × ( 1 + r / 100 ) ^ n where P = Principal, r = Rate (%), n = Years
■ C++ Program
#include<iostream>
#include<cmath> // for pow()
using namespace std;
// r has a DEFAULT value of 50
// If caller skips r, it becomes 50 automatically
double calculateA(double P, int n, double r = 50)
{
double A = P * pow(1 + r / 100.0, n);
return A;
}
int main()
{
double P, r, A;
int n;
// ---- Case 1: User provides P, r, n ----
cout << "Enter Principal (P): ";
cin >> P;
cout << "Enter Rate (r): ";
cin >> r;
cout << "Enter Years (n): ";
cin >> n;
A = calculateA(P, n, r); // all 3 arguments passed
cout << "Amount A = " << A << endl;
cout << "\n--- Using DEFAULT rate (r = 50) ---\n";
// ---- Case 2: r is NOT passed → default 50 is used ----
cout << "Enter Principal (P): ";
cin >> P;
cout << "Enter Years (n): ";
cin >> n;
A = calculateA(P, n); // r uses default = 50
cout << "Amount A = " << A << endl;
return 0;
}
■■ How It Works
• pow(base, exp) from <cmath> computes (1 + r/100)n.
• The function signature double r = 50 sets the default. Default parameters MUST come at the end of
the parameter list.
• First call passes r explicitly. Second call omits r → compiler substitutes 50.
• r/100.0 uses floating-point division to avoid integer truncation.
Question 2: LandMeasure – Passing Objects & Returning Sum
■ Concept: Passing Objects to Functions
Nepal's traditional land system uses: 1 Ropani = 16 Ana | 1 Ana = 4 Paisa | 1 Paisa = 4 Dam. We create
a class LandMeasure to hold a land area and write a function that accepts two such objects and returns
their sum.
Conversion ladder: 1 Ropani = 16 Ana = 64 Paisa = 256 Dam
■ C++ Program
#include<iostream>
using namespace std;
class LandMeasure
{
public:
int ropani, ana, paisa, dam;
// Constructor to set values easily
LandMeasure(int ro=0, int an=0, int pa=0, int da=0)
{
ropani = ro;
ana = an;
paisa = pa;
dam = da;
}
void display()
{
cout << ropani << " Ropani "
<< ana << " Ana "
<< paisa << " Paisa "
<< dam << " Dam" << endl;
}
};
// Function receives two objects → returns sum object
LandMeasure addLand(LandMeasure L1, LandMeasure L2)
{
// Convert everything to Dam (smallest unit)
int totalDam = 0;
totalDam += [Link] * 256 + [Link] * 16 + [Link] * 4 + [Link];
totalDam += [Link] * 256 + [Link] * 16 + [Link] * 4 + [Link];
// Convert back
LandMeasure result;
[Link] = totalDam / 256; totalDam %= 256;
[Link] = totalDam / 16; totalDam %= 16;
[Link] = totalDam / 4; totalDam %= 4;
[Link] = totalDam;
return result; // return by value (a new object)
}
int main()
{
LandMeasure L1(2, 10, 3, 2); // 2 Ropani 10 Ana 3 Paisa 2 Dam
LandMeasure L2(1, 8, 2, 3); // 1 Ropani 8 Ana 2 Paisa 3 Dam
cout << "Land 1: "; [Link]();
cout << "Land 2: "; [Link]();
LandMeasure sum = addLand(L1, L2);
cout << "Sum : "; [Link]();
return 0;
}
■■ How It Works
• Convert all units to Dam (the smallest unit) using multiplication.
• Add both totals, then extract back using integer division and modulo.
• The function returns a new LandMeasure object – C++ copies it out.
• Constructor default args (=0) allow creating an empty object for result.
Question 3: Distance Between Two Points – OOP
■ Concept: OOP with Math
We create a class Point with x and y coordinates. A member function computes the Euclidean distance to
another point.
Distance = sqrt( (x2−x1)² + (y2−y1)² )
■ C++ Program
#include<iostream>
#include<cmath> // sqrt()
using namespace std;
class Point
{
private:
float x, y; // coordinates
public:
// Set the point
void setPoint(float a, float b)
{
x = a;
y = b;
}
// Get x and y
float getX() { return x; }
float getY() { return y; }
// Calculate distance from this point to another Point object
float distanceTo(Point other)
{
float dx = other.x - x;
float dy = other.y - y;
return sqrt(dx*dx + dy*dy);
}
void display()
{
cout << "(" << x << ", " << y << ")";
}
};
int main()
{
Point P1, P2;
float x1, y1, x2, y2;
cout << "Enter coordinates of Point 1 (x y): ";
cin >> x1 >> y1;
[Link](x1, y1);
cout << "Enter coordinates of Point 2 (x y): ";
cin >> x2 >> y2;
[Link](x2, y2);
cout << "\nPoint 1: "; [Link]();
cout << "\nPoint 2: "; [Link]();
cout << "\nDistance = " << [Link](P2) << endl;
return 0;
}
■■ How It Works
• Two Point objects P1 and P2 are created with their (x, y) coordinates.
• distanceTo(Point other) receives a copy of P2 and accesses its private x,y because member
functions have access to all members of the same class.
• sqrt() from <cmath> computes the final Euclidean distance.
• Data is private – good OOP encapsulation; accessed only via methods.
Question 4: mdistance & edistance – Friend Function
■ Concept: Friend Function
A friend function is a non-member function that is given special access to the private data of the classes
that declare it as a friend. Here we add a metric distance (meters + cm) to an English distance (feet +
inches).
1 foot = 30.48 cm | 1 inch = 2.54 cm | Result shown in meters & centimeters
■ C++ Program
#include<iostream>
using namespace std;
// Forward declaration needed because edistance uses mdistance
class edistance;
class mdistance
{
private:
int meter;
float cm;
public:
void setData(int m, float c) { meter = m; cm = c; }
void display()
{
cout << meter << " m " << cm << " cm" << endl;
}
// Declare friend function – it can access BOTH classes' private data
friend mdistance addDistances(mdistance m, edistance e);
};
class edistance
{
private:
int feet;
float inch;
public:
void setData(int f, float i) { feet = f; inch = i; }
void display()
{
cout << feet << " ft " << inch << " inch" << endl;
}
// Same friend declaration in second class
friend mdistance addDistances(mdistance m, edistance e);
};
// Friend function definition – access private members of BOTH classes
mdistance addDistances(mdistance m, edistance e)
{
// Convert edistance to centimeters
float totalCm = [Link] * 30.48f + [Link] * 2.54f;
// Add to mdistance (convert meter to cm first)
float totalAllCm = [Link] * 100.0f + [Link] + totalCm;
mdistance result;
[Link] = (int)(totalAllCm / 100);
[Link] = totalAllCm - [Link] * 100;
return result;
}
int main()
{
mdistance d1;
edistance d2;
[Link](3, 45.0f); // 3 m 45 cm
[Link](2, 6.0f); // 2 ft 6 inch
cout << "Metric distance : "; [Link]();
cout << "English distance : "; [Link]();
mdistance sum = addDistances(d1, d2);
cout << "Sum (in metric) : "; [Link]();
return 0;
}
■■ How It Works
• friend mdistance addDistances(...) is declared inside BOTH classes, granting the function access
to private members of both mdistance and edistance.
• The function converts feet→cm and inches→cm, adds everything, then extracts back to meters+cm.
• Forward declaration class edistance; is needed because mdistance references edistance before it is
fully defined.
• Friend functions are NOT member functions – they don't have a 'this' pointer.
Question 5: Carport – Setter / Getter Members
■ Concept: Class with Setter and Getter Methods
We build a Carport class that tracks parked cars. Each car has a car_id, charge_per_hour (int), and
time (float hours). Two member functions handle setting data and showing charges.
Total Charge = charge_per_hour × time (hours parked)
■ C++ Program
#include<iostream>
using namespace std;
class Carport
{
private:
int car_id;
int charge_hour; // charge per hour in Rs.
float time; // hours parked
public:
// Member 1: SET the data
void setData(int id, int charge, float t)
{
car_id = id;
charge_hour = charge;
time = t;
}
// Member 2: SHOW charges and parked hours for a specific car id
void showData(int search_id)
{
if (car_id == search_id)
{
float total = charge_hour * time;
cout << "Car ID : " << car_id << endl;
cout << "Hours Parked: " << time << " hrs" << endl;
cout << "Total Charge: Rs. " << total << endl;
}
else
{
cout << "Car ID " << search_id << " not found!" << endl;
}
}
};
int main()
{
const int N = 3;
Carport cars[N]; // array of 3 Carport objects
// Set data for each car
cars[0].setData(101, 50, 2.5f);
cars[1].setData(202, 80, 1.0f);
cars[2].setData(303, 60, 3.0f);
int search;
cout << "Enter Car ID to search: ";
cin >> search;
// Check each object
bool found = false;
for (int i = 0; i < N; i++)
{
// We search through all; only matching one prints
if (search == 101 + i*101 || true)
{
// Let showData handle the match logic
}
}
// Simpler: show all, each object checks itself
cout << "\n--- Parking Records ---\n";
for (int i = 0; i < N; i++)
cars[i].showData(search);
return 0;
}
■■ How It Works
• setData() is the setter – it stores car_id, charge_per_hour, and time in private fields.
• showData(search_id) is the getter/display function – each object checks if its own car_id matches
the requested id and prints only if it matches.
• An array of Carport objects (cars[3]) holds multiple cars – real-world pattern.
• Total charge is computed as charge_hour × time inside showData.
• Private data members ensure no direct external access – proper encapsulation.
Question 6: Person Class – Constructor with Logic
■ Concept: Constructor with Conditional Logic
A constructor is a special function that runs automatically when an object is created. Here we initialize all
person data in the constructor and conditionally assign citizenship_number only if age > 16.
Rule: if age > 16 → citizenship_number = provided value | else → citizenship_number = 0
■ C++ Program
#include<iostream>
#include<string>
using namespace std;
class Person
{
private:
string name;
int age;
string address;
int citizenship_number;
public:
// Constructor – runs automatically when object is made
Person(string n, int a, string addr, int cit)
{
name = n;
age = a;
address = addr;
// Conditional assignment based on age
if (age > 16)
citizenship_number = cit;
else
citizenship_number = 0; // not eligible
}
// Display function
void display()
{
cout << "------------------------------" << endl;
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
cout << "Address : " << address << endl;
if (citizenship_number != 0)
cout << "Citizenship: " << citizenship_number << endl;
else
cout << "Citizenship: Not Eligible (Age <= 16)" << endl;
cout << "------------------------------" << endl;
}
};
int main()
{
// Object created → constructor runs immediately
Person P1("Ram Sharma", 22, "Kathmandu", 12345678);
Person P2("Sita Thapa", 15, "Pokhara", 87654321);
Person P3("Hari Bahadur", 17, "Biratnagar", 11223344);
[Link]();
[Link]();
[Link]();
return 0;
}
■■ How It Works
• Person(string n, int a, string addr, int cit) is the parameterized constructor. It takes 4 values and
sets up the object completely.
• The if-else inside the constructor checks age: if age > 16, citizenship is stored; otherwise 0 is
assigned (not eligible).
• P1 (age 22) gets a citizenship number. P2 (age 15) gets 0. P3 (age 17) also gets a citizenship
number.
• All data is private – only the constructor and display() can touch it.
• The display() function also shows a friendly message when citizenship = 0.
■ Quick Summary
Q# Topic Key C++ Concept
Q1 Compound Interest Default Arguments
Q2 Land Measurement Passing / Returning Objects
Q3 Point Distance OOP + cmath
Q4 Metric vs English Friend Function
Q5 Carport Charges Setter / Getter Methods
Q6 Person & Citizenship Constructor + Conditional Logic
■ All programs are beginner-friendly, compile with g++ (C++11 or later), and are exam-ready.