
413 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
MyClasswith a private integer memberdata, a constructor to initialize it, and adisplaymember function to print the value. - We overload the
+operator by defining theoperator+member function. This function takes a constant reference to anotherMyClassobject and returns a newMyClassobject containing the sum of thedatamembers of the two objects. - In the
mainfunction, we create twoMyClassobjects,obj1andobj2, and then add them together using the+operator, resulting in a newMyClassobject,result. - Finally, we display the result using the
displaymember 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.