8

I am being told that I can't use the 'this' keyword in a class function. I'm coming from c# and i'm used to this working, but the compiler tells me that it can only be used within nonstatic member functions.

D3DXVECTOR3 position;

void Position(D3DXVECTOR3 position)
{
    this.position = position;
}
iammilind
  • 68,093
  • 33
  • 169
  • 336
Dollarslice
  • 9,917
  • 22
  • 59
  • 87
  • are you sure it worked in c#? in c#, a 'class function' is called a 'static method', and you cannot use 'this' in those either? – muratgu Sep 29 '11 at 16:25
  • yeah I did it all the time to refer to a classes variable in the constructor, or is the constructor different? – Dollarslice Sep 29 '11 at 16:27
  • Perhaps you should show the class this method belongs to - that might help clarify what you're doing – Useless Sep 29 '11 at 16:31

3 Answers3

19

this is a pointer containing the address of the object.

D3DXVECTOR3 position;

void YourClassNameHere::Position(D3DXVECTOR3 position)
{
    this->position = position;
}

Should work.

D3DXVECTOR3 position;

void YourClassNameHere::Position(D3DXVECTOR3 position)
{
    (*this).position = position;
}

Should also work.

user541686
  • 205,094
  • 128
  • 528
  • 886
Pubby
  • 51,882
  • 13
  • 139
  • 180
16

In C++ you need to qualify your Position function with the class name:

void YourClassNameHere::Position(D3DXVECTOR3 position)

Also from @Pubby8's answer this is a pointer, not a reference so you need to use this->position instead (or consider using parameter names that don't shadow class members - I like using trailing _ on my class members).

Also, C++ doesn't pass by reference by default so if D3DXVECTOR3 is a complicated type you'll be copying a lot of data around. Consider passing it as const D3DXVECTOR3& position instead.

Mark B
  • 95,107
  • 10
  • 109
  • 188
4

Not only is Position a free function (not associated with a class) the way you wrote it, but this is also a pointer, not a reference.

D3DXVECTOR3 position;

void ClassName::Position(D3DXVECTOR3 position)
{
    this->position = position;
}

or, if that's supposed to be a constructor,

ClassName::ClassName(D3DXVECTOR3 p) : position(p)
{
}
Useless
  • 64,155
  • 6
  • 88
  • 132