Skip to main content

Vector class addition by object argument

Short answer

Create a Vector class holding an array and size. The add(Vector) method returns a new Vector with element-wise sum, assuming equal size. For instance, (1,2,3) + (4,5,6) yields (5,7,9).

Using object oriented technique, write a program to create a class vector that reads integer number. Perform vector addition by passing object as argument and returns the object as result. A vector is a class with array as member.

The class Vector has an integer array and its size as members. add() takes a Vector object as an argument and returns a new Vector object holding the element-wise sum. Both vectors are assumed to have the same size.

#include <iostream>
using namespace std;

class Vector {
    int v[20];
    int n;
public:
    void read() {
        cout << "Enter size: ";
        cin >> n;
        cout << "Enter " << n << " elements: ";
        for (int i = 0; i < n; i++)
            cin >> v[i];
    }
    Vector add(Vector b) {          // object passed and returned
        Vector sum;
        sum.n = n;
        for (int i = 0; i < n; i++)
            sum.v[i] = v[i] + b.v[i];
        return sum;
    }
    void display() {
        cout << "(";
        for (int i = 0; i < n; i++) {
            cout << v[i];
            if (i < n - 1) cout << ", ";
        }
        cout << ")" << endl;
    }
};

int main() {
    Vector a, b, c;
    a.read();
    b.read();            // must have the same size as a
    c = a.add(b);
    cout << "Sum = ";
    c.display();
    return 0;
}

Sample run

Enter size: 3
Enter 3 elements: 1 2 3
Enter size: 3
Enter 3 elements: 4 5 6
Sum = (5, 7, 9)

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 1 questions →