0

I cannot figure out why the code isn't executing properly. When i use the function 'adder' inside of the class it does not return the sum which it would have if it were simply run in main as adder(3,1) and defined outside of the class.

class Adder{ public: Adder( int a, int b ) // constructor {a=myValueofA; b=myValueofB; }; int getA() const{ return myValueofA; }; int getB() const{ return myValueofB; }; 

and the recursive addition function

int adder(int x, int y)const { if(x==0) return y; else if(y==0) return x; else return adder(--x,++y); } 

followed by the function that will be called in main.

 int RecursiveAPlusB() const{ return adder(myValueofA, myValueofB); 

private member variables:

int myValueofA; int myValueofB; 

Now onto main()

{ Adder ten( 3, 4 ); // this call should produce 7 but yields 0; cout << ten.RecursiveAPlusB() << endl; return 0;} 

The methods that I used to access variables smelly funny and inefficient (and don't work). Any suggestions? Also note that the driver in main cannot be changed. (Requirement for the assignment.)

1
  • 2
    So should we assume class adder is a mistake, since everywhere else Adder is the name of the class? If it is, please, please, post real code. Commented Aug 2, 2014 at 1:44

1 Answer 1

3

Your constructor is backwards. The code:

Adder( int a, int b ) // constructor {a=myValueofA; b=myValueofB; }; 

puts the value of myValueofA (which hasn't been defined) into the variable a without setting myValueofA, and likewise for myValueofB and b. What you mean to write is:

Adder(int a, int b) { myValueofA = a; myValueofB = b; } // Note that no semicolon is needed after a function definition 

or, even better:

Adder(int a, int b) : myValueofA(a), myValueofB(b) { } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.