0

I'm writing a private member function for a class (function1) and for a chunk of the code I decided it'd be easier to put that chunk into it's own function (function2) , and call it from function1. However, the compiler is saying that function2 needs an object. This doesn't make sense to me, because an object has to be created in order for function1 to work, so the object for function2 seems like it should just be "this".

int ClassName::function1(args)
{
     //some code;
     //some code;

     function2(args);     //says I need an object to call the function here

     //some code;
}

int ClassName::function2(args)
{
     //some code;
}

The exact error code is "A nonstatic member reference must be relative to a specific object". I've been searching for hours and every instance of this comes from someone calling a class member function from outside of the class without using a object pointer. I cannot find anything for a class member function calling another class member function. I also thought I had called member functions from other member functions in the past without trouble, so I'm super confused. I could just delete function2 and do all calculations inside function2, but then I wouldn't learn anything!

I tried switching the order of the function definitions in the cpp file. The order of the prototypes in the header. Changed function2 from private to public. No dice. I've exhausted google, my own programming knowledge, and any experimentation that I could think of, so I have to ask you guys for help now. If you need extra info, let me know, although it seems like the exact code inside my functions would be irrelevant as far as the problem goes.

apxcode
  • 7,696
  • 7
  • 30
  • 41
  • 2
    Is `function1` static? – Jon May 20 '14 at 08:07
  • 2
    @Jon point is correct: I'll add, could you please post the class definition? – sergico May 20 '14 at 08:08
  • function1 is not static. I thought that in order for function1 to be called, it would already have a "this" object, and then "this" would be applied to function2 as well. – user3394004 May 20 '14 at 08:15
  • @user3394004: That's exactly what happens normally, which means that there's a surprise hidden somewhere in the class definition **that you don't show**. – Jon May 20 '14 at 08:18
  • @user3394004 I dont understand your last comment – Govind Balaji May 20 '14 at 08:20
  • Oh gosh. I double checked, and function1 is in fact static. D'oh! So basically it's not working because since function1 is static, it needs to be able to be called even if no object is initialized, and function2 needs to have an object...is that right? And if that's correct, would making function2 static cause the program to work correctly? – user3394004 May 20 '14 at 08:23
  • Making function2 static seems to get rid of the error. I still want to know if my understanding is correct though. – user3394004 May 20 '14 at 08:27
  • @user3394004: It is, more or less. – Jon May 20 '14 at 08:36

0 Answers0