Engine
Engine

Reputation: 5422

how can I use a non static instance in a static method in c++?

I have a an instance of lasse1 and I want to use it in a method of lasse2 , this method is static method, this just doesn't work :

 class Lasse2{
 ......
public :
static void function(void);
Lasse1* obj;
........
};

And now i want to use it like :

void Lasse2::function(void){
obj->dosmt(); // this doesn't work 
.........

any idea how can I solve this?

Upvotes: 0

Views: 81

Answers (4)

Marshall Clow
Marshall Clow

Reputation: 16670

SLaks said it best: "You can't"

Here's why:

When you declare a member variable (not static, see obj above), you're telling the compiler that each object of type Lassie2 contains a pointer to a Lassie1.

When you declare a method static, that means that it is independent of all the instances (the actual objects) of that class. It doesn't operate on an object.

So inside of Lasse2::function, there's no this, no Lassie2 object for you to get the obj pointer from.

Upvotes: 0

Peter Ruderman
Peter Ruderman

Reputation: 12485

If you want to access an instance member of your class, then you must have an instance of that class. There's no way around this. Your options are:

  1. Make obj a static member. Do this if you intend to have a single obj for all instances of this class.
  2. Remove static from function() so it becomes an instance method.

If you can't do either of those, then you need to find a way to pass an instance pointer to your function. For example, APIs that require a function pointer often have a mechanism for passing pointer-sized data to that function when it's eventually called.

Upvotes: 2

Macke
Macke

Reputation: 25680

You need an instance of your class to pull that off.

Create one or receive it through other means (function argument, global variable, class static variable, etc)

Upvotes: 1

Mark B
Mark B

Reputation: 96241

Change your static method to explicitly pass the object pointer:

static void function(Lasse1* obj)
{
    obj->dosmt(); 
}

But before you do, consider what you're really trying to do (and even write another question if you like).

Upvotes: 1

Related Questions