- 2069 Chaitra · 5 marks
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)
Related questions
- Overload index operator [] for array class · Object Oriented Programming, chapter 5
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Array class template with max, min, sort · Object Oriented Programming, chapter 9
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Default argument and overloading program · Object Oriented Programming, chapter 3
- Exception with argument and specification program · Object Oriented Programming, chapter 10
- Create classes from design class diagrams · Object Oriented Analysis and Design, chapter 4 · asked 2×
- Object oriented system and core concepts · Object Oriented Analysis and Design, chapter 1
- Algorithmic vs object-oriented decomposition · Object Oriented Analysis and Design, chapter 1
- Insert number at position in array · Computer Programming, chapter 11