0 votes
91 views
in Practical Questions by (98.9k points)
Practical session(constructor & operator overloading)

1 Answer

0 votes
by (98.9k points)
 
Best answer

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;
}

 

Related questions

0 votes
1 answer 109 views
+2 votes
1 answer 209 views
0 votes
1 answer 127 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

559 users

...