Cover Image for Adding Two Objects in C++
167 views

Adding Two Objects in C++

The C++can add two objects of a user-defined class by defining an appropriate addition operator (operator+) for that class. Here’s an example of how to add two objects of a custom class:

C++
#include <iostream>

class MyClass {
public:
    MyClass(int value) : data(value) {}

    // Overload the addition operator (+) for adding two objects
    MyClass operator+(const MyClass& other) const {
        return MyClass(data + other.data);
    }

    void display() const {
        std::cout << "Data: " << data << std::endl;
    }

private:
    int data;
};

int main() {
    MyClass obj1(5);
    MyClass obj2(10);

    MyClass result = obj1 + obj2; // Add two objects

    std::cout << "Result of addition: ";
    result.display();

    return 0;
}

In this example:

  • We define a class called MyClass with a private integer member data, a constructor to initialize it, and a display member function to print the value.
  • We overload the + operator by defining the operator+ member function. This function takes a constant reference to another MyClass object and returns a new MyClass object containing the sum of the data members of the two objects.
  • In the main function, we create two MyClass objects, obj1 and obj2, and then add them together using the + operator, resulting in a new MyClass object, result.
  • Finally, we display the result using the display member function.

When you run this program, it will add the data members of obj1 and obj2 and display the result, which should be 15 in this case. You can customize the class and the addition operation to suit your specific needs.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS