0

I have a method run() member of MyClass. At compilation, i get

    Error   3   error C2662: 'MyClass::run' : 
    cannot convert 'this' pointer from 'const MyClass' to 'MyClass&'

ITOH, if I put make this method static, i have no error. Method call occurs here:

Errors MyClass::execute( const AbstractExecutionContext &ctx ) const
{
    Errors errs;

    Watch wat; wat.restart();
    {

        run() ;

    }

    return errs;
}

and declaration for this method is

Errors execute(const AbstractExecutionContext &ctx) const;

I wish i can make this method not static, because if it is static, methods called by run() must be static as well, and data members that are non static cannot be accessed (i have to uglyly pass them as arguments to methods).

What is the reason for compilation error, and what would be a solution ?

kiriloff
  • 25,609
  • 37
  • 148
  • 229

1 Answers1

8

run must be const too. or function execute should not be const.

In your execute function this is const MyClass* const this. When run is not static and not const - there is attempt to call non-const function of const object. If run is static - all works fine, since static functions has no this pointer.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 7
    Static methods don't have a this pointer, there's no object state to keep constant. – Paul Rubel Apr 09 '13 at 12:29
  • lets say my solution is to make all methods called by run() static, and that i make all data member i need static as well. then is it possible to change value for this data members at run time ? – kiriloff Apr 09 '13 at 12:33
  • @antitrust yes, but static members's owner is CLASS, not OBJECT. – ForEveR Apr 09 '13 at 12:34
  • is it possible then to change value for static member at any time with MyClass::member = val ; ? – kiriloff Apr 09 '13 at 12:42
  • is it more appropriate to have data member that i pass as arguments of all static methods – kiriloff Apr 09 '13 at 12:46