Constructor and Operator Overloading for a Simple Class:
#include <iostream>
class ComplexNumber {
private:
double real;
double imaginary;
public:
ComplexNumber() : real(0.0), imaginary(0.0) {}
ComplexNumber(double r, double i) : real(r), imaginary(i) {}
// Overloading the + operator
ComplexNumber operator+(const ComplexNumber& other) const {
return ComplexNumber(real + other.real, imaginary + other.imaginary);
}
// Overloading the - operator
ComplexNumber operator-(const ComplexNumber& other) const {
return ComplexNumber(real - other.real, imaginary - other.imaginary);
}
// Overloading the << operator for output
friend std::ostream& operator<<(std::ostream& os, const ComplexNumber& complex) {
os << complex.real << " + " << complex.imaginary << "i";
return os;
}
};
int main() {
ComplexNumber c1(2.0, 3.0);
ComplexNumber c2(1.0, -1.0);
ComplexNumber sum = c1 + c2;
ComplexNumber difference = c1 - c2;
std::cout << "c1: " << c1 << std::endl;
std::cout << "c2: " << c2 << std::endl;
std::cout << "Sum: " << sum << std::endl;
std::cout << "Difference: " << difference << std::endl;
return 0;
}
Constructor Overloading for a Class with Multiple Constructors:
#include <iostream>
class Rectangle {
private:
double length;
double width;
public:
Rectangle() : length(0.0), width(0.0) {}
Rectangle(double l, double w) : length(l), width(w) {}
double area() const {
return length * width;
}
double perimeter() const {
return 2 * (length + width);
}
};
int main() {
Rectangle defaultRect;
Rectangle customRect(5.0, 3.0);
std::cout << "Default Rectangle - Area: " << defaultRect.area() << ", Perimeter: " << defaultRect.perimeter() << std::endl;
std::cout << "Custom Rectangle - Area: " << customRect.area() << ", Perimeter: " << customRect.perimeter() << std::endl;
return 0;
}