Click here to Skip to main content
15,939,243 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<iostream> 
using namespace std;
class ComplexNum{
    //public:
    int a,b;
    public:
    void getData(){
        cin >> a >> b;
    }
    
    void getSum(ComplexNum n1, ComplexNum n2, ComplexNum n3){
        n3.a = n2.a + n1.a;
        n3.b = n2.b + n1.b; 
    }
    
 
    void display(){
        cout << "a = " <<a <<" " << "b = " <<b;}
};
int main(){
  ComplexNum n1, n2, n3;
  n1.getData();
  n2.getData();
  n3.getSum(n1,n2,n3);
  n3.display();
    return 0;
}
according to me (I may be wrong) this function is supposed to return n3 which is vector sum of n1 and n2 but it is returning some garbage value. Please help

What I have tried:

i dont know what to do to solve this issue :|
Posted
Updated 5-Oct-20 6:40am
v3

1 solution

The problem is you are modifying a ComplexNum object passed by value (that is the calling code won't see the changes). You should pass it by reference, instead.
Change
Quote:
void getSum(ComplexNum n1, ComplexNum n2, ComplexNum n3){
To
C++
void getSum(const ComplexNum & n1, const ComplexNum & n2, ComplexNum & n3){
in order to fix your code.



Anyway you may also consider overloading the + operator:
C++
#include<iostream>
using namespace std;

class ComplexNum
{
  int a,b;
public:
  void getData()
  {
    cin >> a >> b;
  }

  friend ComplexNum  operator + (const ComplexNum &, const ComplexNum &);

  void display()
  {
        cout << "a = " <<a <<" " << "b = " <<b;
  }
};


ComplexNum operator + (const ComplexNum & c1, const ComplexNum & c2)
{
  ComplexNum r;
  r.a = c1.a + c2.a;
  r.b = c1.b + c2.b;
  return r;
}


int main()
{
  ComplexNum n1, n2, n3;
  n1.getData();
  n2.getData();
  n3 = n1 + n2;
  n3.display();

  return 0;
}
 
Share this answer
 
v3
Comments
KarstenK 5-Oct-20 12:42pm    
ComplexNum& operator + would be perfect ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900