kiriloff
kiriloff

Reputation: 26333

C++ static method needed

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 ?

Upvotes: 0

Views: 190

Answers (1)

ForEveR
ForEveR

Reputation: 55887

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.

Upvotes: 8

Related Questions