tzippy
tzippy

Reputation: 6638

Using this pointer in const member function (C++)

I have a const member function bar from within I want to use the this pointer to call a function of a base class of ClFoo.

I get a compiler error though, saying:

'ClRDFoo::ReadCounterfile' : cannot convert 'this' pointer from 'const ClFoo' to 'ClRDLFoo &'   

These are the methods and classes:

//ClFoo.cpp

int ClFoo::bar( void ) const
{
    int nCounter = 0;
    this->ReadCounterFile(&nCounter);
}

//ClFoo.h

class ClFoo : public ClRDFoo
{
protected: 

      int ClFoo::bar( void ) const;

}

//ClRDFoo.h

  class ClRDFoo 
    {

    protected:
         virtual bool ReadCounterFile(void *pBuffer);

    }

Upvotes: 0

Views: 581

Answers (3)

Saby
Saby

Reputation: 718

From bar() function which is a constant, you are calling a non constant function ReadCounterFile(), which is not allowed

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

Because bar is marked const, all it can do is call other functions also marked const. This is to ensure that you do not modify anything.

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227418

You are trying to call a non-const member function, (bool ReadCounterFile(void*)), from a const one (void bar() const). This breaks const correctness and is not allowed.

You would have to make ReadCounterFile const or make bar() non-const.

Upvotes: 3

Related Questions