OOP CPP Lab Test Complete Solutions
OOP CPP Lab Test Complete Solutions
This document contains solutions for all 25 practical questions in the OOP Lab Test. Each solution
Student Class
Solution:
#include <iostream>
using namespace std;
class Student {
string name;
int rollNumber;
float marks;
public:
void setDetails(string n, int r, float m) {
name = n;
rollNumber = r;
marks = m;
}
void display() {
cout << "Name: " << name << "\nRoll No: " << rollNumber << "\nMarks: " << marks
<< endl;
}
};
int main() {
Student s1;
s1.setDetails("John Doe", 101, 89.5);
s1.display();
return 0;
}
Rectangle Class
Solution:
#include <iostream>
using namespace std;
class Rectangle {
float length, width;
public:
void setValues(float l, float w) {
length = l;
width = w;
}
float area() { return length * width; }
float perimeter() { return 2 * (length + width); }
};
int main() {
Rectangle rect;
rect.setValues(5.5, 3.2);
cout << "Area: " << rect.area() << "\nPerimeter: " << rect.perimeter() << endl;
return 0;
}
Solution:
#include <iostream>
using namespace std;
class Circle {
float radius;
public:
Circle() { radius = 1.0; }
Circle(float r) { radius = r; }
float area() { return 3.14 * radius * radius; }
};
int main() {
Circle c1, c2(5);
cout << "Default Circle Area: " << c1.area() << "\nCustom Circle Area: " <<
c2.area() << endl;
return 0;
}
Solution:
#include <iostream>
using namespace std;
class BankAccount {
string accHolder;
int accNumber;
float balance;
public:
BankAccount(string name, int acc, float bal) {
accHolder = name;
accNumber = acc;
balance = bal;
}
void deposit(float amount) { balance += amount; }
void withdraw(float amount) { if (amount <= balance) balance -= amount; }
void display() { cout << "Account Holder: " << accHolder << "\nBalance: " << balance
<< endl; }
};
int main() {
BankAccount acc("Alice", 12345, 5000);
acc.deposit(1000);
acc.withdraw(500);
acc.display();
return 0;
}
Solution:
#include <iostream>
using namespace std;
class Complex {
float real, imag;
public:
Complex(float r = 0, float i = 0) { real = r; imag = i; }
Complex operator+(Complex const &obj) {
return Complex(real + obj.real, imag + obj.imag);
}
void display() { cout << real << " + " << imag << "i" << endl; }
};
int main() {
Complex c1(3, 4), c2(1, 2), c3;
c3 = c1 + c2;
c3.display();
return 0;
}