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

Complex: o o o o

The document outlines a series of programming exercises focused on C++ object-oriented programming concepts, including class creation, inheritance, polymorphism, operator overloading, and exception handling. Each exercise includes a specific question and objective, along with example implementations for various classes such as Complex, Shape, Matrix, Polynomial, Vector, Division, Pair, Statistics, BankAccount, and Student. The exercises aim to reinforce fundamental OOP principles and practices in C++.

Uploaded by

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

Complex: o o o o

The document outlines a series of programming exercises focused on C++ object-oriented programming concepts, including class creation, inheritance, polymorphism, operator overloading, and exception handling. Each exercise includes a specific question and objective, along with example implementations for various classes such as Complex, Shape, Matrix, Polynomial, Vector, Division, Pair, Statistics, BankAccount, and Student. The exercises aim to reinforce fundamental OOP principles and practices in C++.

Uploaded by

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

1.

Basic Class Creation

• Question: Write a Complex class to represent complex numbers. The class should have:
o Private attributes for the real and imaginary parts.
o Constructors for initializing these values.
o Member functions to add, subtract, and multiply two complex numbers.
o Overloaded << operator for outputting a complex number in the form "a + bi".
• Objective: This question reinforces encapsulation, constructors, and operator overloading.

2. Inheritance and Polymorphism

• Question: Create a base class Shape with a pure virtual function area(). Then, implement derived classes
Circle, Rectangle, and Triangle, each overriding the area() function to return the area of the
specific shape.
o Add appropriate constructors and functions to set dimensions.
o Write a main function to dynamically create an array of pointers to Shape objects and calculate their areas.
• Objective: This introduces polymorphism and abstract classes.

3. Operator Overloading for Mathematical Objects

• Question: Implement a Matrix class with:


o Attributes for the number of rows and columns and a dynamic 2D array for elements.
o Member functions for matrix addition and scalar multiplication.
o Overloaded + and * operators to handle these operations.
• Objective: Teaches operator overloading and the use of dynamic memory management.

4. Class Composition and Nested Classes

• Question: Create a Polynomial class that represents a polynomial equation. The class should contain a
Term nested class with private attributes for the coefficient and exponent.
o Implement a function to add terms to the polynomial.
o Implement an evaluate function that takes a value of x and returns the evaluated result of the polynomial.
• Objective: Demonstrates class composition and handling mathematical expressions.

5. Static Members and Functions

• Question: Design a Vector class that represents a vector in 3D space. Include:


o Private attributes for the vector components.
o Static members to keep track of the number of vectors created.
o A static function to return the total number of vectors.
• Objective: Teaches the use of static members and functions.

6. Exception Handling in Mathematical Computation

• Question: Create a Division class with a function to divide two numbers and throw an exception if the
denominator is zero.
o Catch the exception in main() and display an appropriate message.
• Objective: Introduces exception handling in mathematical contexts.

Page 1 of 9
7. Template Class for Mathematical Structures

• Question: Implement a template class Pair that can store any pair of mathematical objects (like two
integers or two matrices).
o Include a function to find the sum of the two elements if they are of numeric types.
• Objective: Introduces students to templates and generic programming.

8. Function Overloading in Mathematics

• Question: Write a class Statistics that provides overloaded functions to calculate the mean, median,
and standard deviation for:
o A vector of integers.
o A vector of doubles.
o An array of integers (using pointers).
• Objective: Teaches function overloading, handling multiple data types, and mathematical functions in a
class.

9. Simple Class for a Bank Account

• Question: Design a BankAccount class with:


o Private attributes for accountNumber and balance.
o Public functions to deposit and withdraw amounts, and a function to display the balance.
o Ensure that withdraw checks if there are sufficient funds.
• Objective: This reinforces encapsulation and basic function implementation in a real-world scenario.

10. Encapsulation with Getters and Setters

• Question: Create a class Student with private attributes name, rollNumber, and grade.
o Implement public getter and setter functions for each attribute.
o In the main function, demonstrate creating a Student object, setting values, and printing them.
• Objective: Helps students understand encapsulation and the role of getters and setters.

Page 2 of 9
== Solutions ==

1. Basic Class Creation: Complex Class

cpp
Copy code
#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

Complex add(const Complex& other) {


return Complex(real + other.real, imag + other.imag);
}

Complex subtract(const Complex& other) {


return Complex(real - other.real, imag - other.imag);
}

Complex multiply(const Complex& other) {


return Complex(real * other.real - imag * other.imag,
real * other.imag + imag * other.real);
}

friend ostream& operator<<(ostream& os, const Complex& c) {


os << c.real << " + " << c.imag << "i";
return os;
}
};

2. Inheritance and Polymorphism: Shape Base Class

cpp
Copy code
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

class Shape {
public:
virtual double area() const = 0; // Pure virtual function

Page 3 of 9
virtual ~Shape() = default;
};

class Circle : public Shape {


private:
double radius;

public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
};

class Rectangle : public Shape {


private:
double length, width;

public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() const override {
return length * width;
}
};

class Triangle : public Shape {


private:
double base, height;

public:
Triangle(double b, double h) : base(b), height(h) {}
double area() const override {
return 0.5 * base * height;
}
};

int main() {
vector<Shape*> shapes = {new Circle(5), new Rectangle(4, 6), new
Triangle(3, 4)};
for (Shape* shape : shapes) {
cout << "Area: " << shape->area() << endl;
delete shape;
}
return 0;
}

3. Operator Overloading: Matrix Class

cpp
Page 4 of 9
Copy code
#include <iostream>
#include <vector>
using namespace std;

class Matrix {
private:
int rows, cols;
vector<vector<int>> mat;

public:
Matrix(int r, int c) : rows(r), cols(c), mat(r, vector<int>(c, 0))
{}

Matrix operator+(const Matrix& other) {


Matrix result(rows, cols);
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
result.mat[i][j] = mat[i][j] + other.mat[i][j];
return result;
}

Matrix operator*(int scalar) {


Matrix result(rows, cols);
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
result.mat[i][j] = mat[i][j] * scalar;
return result;
}
};

4. Class Composition: Polynomial Class

cpp
Copy code
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class Polynomial {
private:
class Term {
public:
double coefficient;
int exponent;
Term(double c, int e) : coefficient(c), exponent(e) {}
};

Page 5 of 9
vector<Term> terms;

public:
void addTerm(double coef, int exp) {
terms.push_back(Term(coef, exp));
}

double evaluate(double x) const {


double result = 0;
for (const auto& term : terms)
result += term.coefficient * pow(x, term.exponent);
return result;
}
};

5. Static Members and Functions: Vector Class

cpp
Copy code
#include <iostream>
using namespace std;

class Vector {
private:
double x, y, z;
static int count;

public:
Vector(double x = 0, double y = 0, double z = 0) : x(x), y(y),
z(z) {
++count;
}

static int getCount() {


return count;
}
};

int Vector::count = 0;

6. Exception Handling: Division Class

cpp
Copy code
#include <iostream>
#include <stdexcept>
using namespace std;
Page 6 of 9
class Division {
public:
double divide(double numerator, double denominator) {
if (denominator == 0) throw runtime_error("Division by zero");
return numerator / denominator;
}
};

int main() {
Division div;
try {
cout << div.divide(10, 0) << endl;
} catch (const exception& e) {
cout << e.what() << endl;
}
return 0;
}

7. Template Class: Pair Class

cpp
Copy code
#include <iostream>
using namespace std;

template <typename T>


class Pair {
private:
T first, second;

public:
Pair(T f, T s) : first(f), second(s) {}

T sum() const {
return first + second;
}
};

8. Function Overloading: Statistics Class

cpp
Copy code
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
Page 7 of 9
class Statistics {
public:
double mean(const vector<int>& data) { /* ... */ }
double mean(const vector<double>& data) { /* ... */ }
double mean(const int* data, int size) { /* ... */ }
// Implement median and standard deviation similarly
};

9. Simple Bank Account: BankAccount Class

cpp
Copy code
#include <iostream>
using namespace std;

class BankAccount {
private:
int accountNumber;
double balance;

public:
BankAccount(int acc, double bal = 0) : accountNumber(acc),
balance(bal) {}

void deposit(double amount) { balance += amount; }


bool withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
return true;
} else {
cout << "Insufficient funds." << endl;
return false;
}
}
void display() const { cout << "Balance: " << balance << endl; }
};

10. Encapsulation: Student Class

cpp
Copy code
#include <iostream>
using namespace std;

class Student {
private:
Page 8 of 9
string name;
int rollNumber;
char grade;

public:
void setName(const string& n) { name = n; }
void setRollNumber(int r) { rollNumber = r; }
void setGrade(char g) { grade = g; }

string getName() const { return name; }


int getRollNumber() const { return rollNumber; }
char getGrade() const { return grade; }
};

int main() {
Student s;
s.setName("John");
s.setRollNumber(1);
s.setGrade('A');
cout << "Name: " << s.getName() << ", Roll: " << s.getRollNumber()
<< ", Grade: " << s.getGrade() << endl;
return 0;
}

These implementations cover each question and fulfill the objective of introducing basic to intermediate
C++ OOP concepts.

Page 9 of 9

You might also like