views:

71

answers:

4

Hi,

I want to const declare the this pointer received as an argument.

static void Class::func(const OtherClass *otherClass) 
{ 
   // use otherClass pointer to read, but not write to it.
}

It is being called like this:

void OtherClass::func()
{
  Class::func(this);
}

This does not compile nad if i dont const declare the OtherClass pointer, I can change it.

Thanks.

+2  A: 

You cannot define static class memberv functions like this:

static void Class::func(const OtherClass *otherClass) 
{ 
   // use otherClass pointer to read, but not write to it.
}

The function must be declared static in the class declaration, and then the function definition looks like:

void Class::func(const OtherClass *otherClass) 
{ 
   // use otherClass pointer to read, but not write to it.
}
anon
A: 

This compiles fine on my machine:

#include <iostream>

class bar;

class foo {
public:
    static void f(const bar* b) { std::cout << b << '\n'; }
};

class bar {
public:
    void f() {foo::f(this);}
};

int main(void)
{
    bar b;
    b.f();
    return 0;
}

So what do you have done differently?

sbi
A: 

When dealing with const and pointers, the trick is to read right-to-left. Check out http://www.parashift.com/c++-faq-lite/const-correctness.html for a good overview.

Per Fagrell
A: 

If you won't change the pointer or the object pointed to, why not take a const reference instead?

void Class::func(const OtherClass& otherClass) 
{ 
   // use otherClass ref for read-only use of OtherClass
}
void OtherClass::func()
{
  Class::func(*this);
}
AngryWhenHungry