15 Complete Programs with Detailed Explanations
C++ · Object-Oriented Programming · BCA / B.TechDemonstrates basic class creation with private data members and public member functions in C++.
#include <iostream>
using namespace std;
class Student {
int roll;
string name;
float marks;
public:
void input() {
cout << "Enter Roll No, Name and Marks: ";
cin >> roll >> name >> marks;
}
void display() {
cout << "\nStudent Details:\n";
cout << "Roll No: " << roll << endl;
cout << "Name: " << name << endl;
cout << "Marks: " << marks << endl;
}
};
int main() {
Student s;
s.input();
s.display();
return 0;
}
roll, name, marks are private by default; they cannot be accessed directly from outside the class.input() and display() are accessible outside the class.cin and stores them in the object's data members.s of type Student; member functions are called using the dot operator.Shows both a Default Constructor and a Parameterized Constructor inside a single class.
#include <iostream>
using namespace std;
class Box {
int length;
public:
Box() { length = 0; } // Default Constructor
Box(int l) { length = l; } // Parameterized Constructor
void show() {
cout << "Length: " << length << endl;
}
};
int main() {
Box b1; // calls Default Constructor -> length = 0
Box b2(10); // calls Parameterized Constructor -> length = 10
b1.show();
b2.show();
return 0;
}
length = 0. Called when you write Box b1;length. Called as Box b2(10);void.A non-member function that is granted access to private and protected members of a class.
#include <iostream>
using namespace std;
class Test {
int x; // private member
public:
Test(int a) { x = a; }
friend void show(Test t); // grant access to show()
};
// show() is NOT a member, but can access private 'x'
void show(Test t) {
cout << "Value of x: " << t.x << endl;
}
int main() {
Test t1(5);
show(t1); // calling the friend function
return 0;
}
friend, t.x inside show() would cause a compile error.show() can access Test's members, but not vice versa.An object of a class is passed as a parameter to a member function of the same class.
#include <iostream>
using namespace std;
class Distance {
int meter;
public:
Distance(int m) { meter = m; }
void add(Distance d) {
cout << "Total Distance: " << meter + d.meter
<< " meters" << endl;
}
};
int main() {
Distance d1(5), d2(6);
d1.add(d2); // d2 is passed as an argument to d1's method
return 0;
}
add(), meter refers to d1.meter (the calling object), and d.meter refers to d2.meter (the argument).d2 is made; changes inside add() do not affect the original d2.Multiple functions share the same name but differ in the number or type of parameters — compile-time polymorphism.
#include <iostream>
using namespace std;
class Area {
public:
// One argument -> area of a square
void calc(int s) {
cout << "Area of Square: " << s * s << endl;
}
// Two arguments -> area of a rectangle
void calc(int l, int b) {
cout << "Area of Rectangle: " << l * b << endl;
}
};
int main() {
Area a;
a.calc(4); // calls calc(int s)
a.calc(3, 5); // calls calc(int l, int b)
return 0;
}
Redefines the + operator to add two Complex number objects.
#include <iostream>
using namespace std;
class Complex {
int real, imag;
public:
Complex(int r, int i) {
real = r;
imag = i;
}
// Overload the + operator
Complex operator+(Complex c) {
return Complex(real + c.real, imag + c.imag);
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2; // invokes operator+()
c3.display();
return 0;
}
operator+; called when c1 + c2 is written.Complex object holding the summed values.c1.operator+(c2); real = 1+3 = 4, imag = 2+4 = 6.c1 and c2 remain unchanged; the result is stored in c3.Overloads the unary - operator to negate a Number object's value.
#include <iostream>
using namespace std;
class Number {
int n;
public:
Number(int x) { n = x; }
// Overload unary minus operator
void operator-() {
n = -n;
}
void show() {
cout << "Value: " << n << endl;
}
};
int main() {
Number obj(5);
-obj; // invokes operator-() -> n becomes -5
obj.show();
return 0;
}
-, ++, !).obj.operator-(), which flips the sign of n.n changes from 5 to −5 inside the same object.operator+ takes one parameter (the right operand); unary takes none.Enables runtime polymorphism — the correct overridden function is called through a base-class pointer.
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base Class" << endl;
}
};
class Derived : public Base {
public:
void show() { // overrides Base::show()
cout << "Derived Class" << endl;
}
};
int main() {
Base* b; // pointer to Base
Derived d;
b = &d; // base pointer points to Derived object
b->show(); // calls Derived::show() (runtime polymorphism)
return 0;
}
b->show() would call Base::show() regardless of what b points to.b actually points to a Derived object, Derived::show() is called.Declares an interface using = 0; forces derived classes to provide their own implementation.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void area() = 0; // Pure Virtual Function
};
class Circle : public Shape {
public:
void area() { // must provide implementation
cout << "Area of Circle = 3.14 * r * r" << endl;
}
};
int main() {
// Shape s; // ERROR: cannot instantiate abstract class
Circle c;
c.area();
return 0;
}
virtual void area() = 0;; has no body in the base class.Circle provides area(), so it is a concrete class and can be instantiated.Shape* pointer can point to any shape, enabling generic programming.A derived class inherits properties and behaviours from one base class — the simplest form of inheritance.
#include <iostream>
using namespace std;
class Person {
public:
string name;
};
class Student : public Person { // Student inherits Person
public:
void get() {
cout << "Enter Name: ";
cin >> name; // 'name' inherited from Person
}
void show() {
cout << "Name: " << name << endl;
}
};
int main() {
Student s;
s.get();
s.show();
return 0;
}
Student ← Person).Person remain public in Student.name is defined in Person, but Student can use it directly.name in Student; inheritance provides it automatically.Student IS-A Person; this real-world relationship maps naturally to inheritance.A chain of classes where B inherits A, and C inherits B — forming a grandparent → parent → child hierarchy.
#include <iostream>
using namespace std;
class A {
public:
void showA() { cout << "Class A\n"; }
};
class B : public A { // B inherits A
public:
void showB() { cout << "Class B\n"; }
};
class C : public B { // C inherits B (and thus A)
public:
void showC() { cout << "Class C\n"; }
};
int main() {
C obj;
obj.showA(); // inherited from A (via B)
obj.showB(); // inherited from B
obj.showC(); // own method
return 0;
}
obj of type C can access members of A, B, and C all at once.Uses try, throw, and catch to gracefully handle a divide-by-zero error.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 0;
try {
if (b == 0)
throw b; // throw an int exception
cout << a / b; // this line is skipped
}
catch (int) {
cout << "Error: Division by zero!" << endl;
}
return 0;
}
catch if an exception is thrown.int; the value b is passed to the handler.int-type exception; multiple catch blocks can handle different types.b != 0, throw is never reached and division happens normally.A generic function that works with any data type — write once, use with int, float, string, etc.
#include <iostream>
using namespace std;
template <class T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << "Maximum (int): " << maximum(5, 9) << endl;
cout << "Maximum (float): " << maximum(3.7f, 2.1f) << endl;
return 0;
}
T; the compiler substitutes the real type when the function is called.int version automatically: int maximum(int, int).float version automatically.maximum for each data type.vector<T>.A generic class whose data type is determined at instantiation time using template <class T>.
#include <iostream>
using namespace std;
template <class T>
class Test {
T x;
public:
Test(T a) { x = a; }
void show() {
cout << "Value: " << x << endl;
}
};
int main() {
Test<int> t1(10);
Test<float> t2(3.14f);
Test<string> t3("Hello");
t1.show();
t2.show();
t3.show();
return 0;
}
T is a parameter.int-specialised version of Test.float version is generated automatically.vector<int>, stack<string> are all class templates from the Standard Library.Writes data to a file using ofstream and reads it back using ifstream — persistent storage in C++.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// --- WRITE to file ---
ofstream fout("data.txt");
fout << "Hello, File Handling!";
fout.close();
// --- READ from file ---
ifstream fin("data.txt");
string line;
cout << "Reading from file:\n";
while (getline(fin, line)) {
cout << line << endl;
}
fin.close();
return 0;
}
ofstream (output file stream) and ifstream (input file stream).line; the loop continues until EOF.