0

C++ OOP: output issue

I have one header file and a source file. I have declared my variables in header file and I am trying to implement them in my source file. I am trying to add the to values of variable a and b but the output is 0 for some reason. Any idea as why is 0 the output even though I am trying to return a + b. my header file (sum.h) code is below: class sum { private: int a; int b; public: int add_numbers(); int setValues(int a, int b); }; my source file is code is below ( .cpp) #include <iostream> #include "sum.h" using namespace std; int sum::add_numbers() { return a + b; } int setValues( int a = 6, int b = 8); int main() { sum test; cout << test.add_numbers()<<endl; return 0; }

6th Sep 2022, 10:56 AM
Humza Ali
Humza Ali - avatar
2 Answers
+ 2
To make things easier, I think you can make a parametric constructor that accepts values for <a> and <b>. This way you can setup <a> and <b> as the object is constructed, rather than having to call setValues() before calling add_numbers(). If you want to use sum::setValues() then you should define it in source file cause it doesn't seem to be defined in there. You have this line ... int setValues( int a = 6, int b = 8 ); Which is a forward declaration of a free function, not a member of class `sum`. It should've been something like ... int sum::setValues( int a = 6, int b = 8 ) { // code here ... } But even with this, you'd still have to call setValues() before add_numbers() - in order for <a> and <b> to be properly initialized. That was why I suggest you to make a parametric constructor instead. I also think that setValues() return type should be defined as `void` because it's a setter. Unless you want the return value to represent a status, whether the given arguments were valid, or not.
6th Sep 2022, 11:33 AM
Ipang
+ 1
Humza Ali you did not define setValues. #include <iostream> using namespace std; class Sum { private: int a; int b; public: void setValues(int x, int y); int add_numbers(); }; int Sum::add_numbers() { return a + b; } void Sum::setValues(int x, int y) { a = x; b = y; } int main() { Sum test; test.setValues(6, 8); cout << test.add_numbers()<<endl; }
6th Sep 2022, 11:48 AM
Bob_Li
Bob_Li - avatar