views:

112

answers:

3

having a file containing these statements:

public:
boost::shared_ptr<TBFControl::TbfCmdHandler> _tbfCmdHandlerPtr;
// will be private later...

boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler()
{ return _tbfCmdHandlerPtr; }

I can use it this way:

boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandlerPtr(
    this->getTBFInstallation()-> _tbfCmdHandlerPtr );

but not, like i want, this way:

boost::shared_ptr<TBFControl::TbfCmdHandler>myTbfCmdHandlerPtr(
    this->getTBFInstallation()->getTBFCmdHandler() );

Using the getter function, the following error occurs:

'Housekeeping::TBFInstallation::getTBFCmdHandler' : cannot convert 'this' pointer from 'const Housekeeping::TBFInstallation' to 'Housekeeping::TBFInstallation &'

what is going wrong here?

+7  A: 

Obviously, this->getTBFInstallation() returns a const pointer. You need to make the function getTBFCmdHandler const as well.

boost::shared_ptr<TBFControl::TbfCmdHandler> getTBFCmdHandler() const
{
    return _tbfCmdHandlerPtr;
}

Note the const keyword at the end of the first line.

Edit: By adding const, you're in effect changing the type of this from TBFInstallation * to TBFInstallation const *. Basically, by adding the const, you're saying that the function can be called even when the object on which the function is being called is const.

avakar
Either that or make getTBFInstallation return a non-const ...
Goz
Goz, yes, that would work too. Since `getTBFCmdHandler` is a getter function, however, it's probably better to do it my way.
avakar
it works, but i did not understand why I have to write the const at the end of the function, i would had assumed to write const before the function, but that did not work.
Christoferw
The const at the end basically says you have a constant this pointer. If you are calling on a const class pointer than the function needs a const this or it won't work ...
Goz
+1  A: 

getTBFInstallation() is (apparently) returning a const pointer. However, getTBFCmdHandler() is a non-const member function and can therefore not be called on a const pointer. Solution: Make getTBFCmdHandler() a const member function

Martin B
+1  A: 

Without having seen the code I would guess that getTBFInstallation() returns a const TBFInstallation on which you're trying to call a non const function.

Andreas Brinck