c++getterconst-cast

How to use the non-const getter if there's a const one too?


If I have a class with getters of return type both const and non-const, how can I use the non-const one?

The class (MeshManipulator.h):

namespace vortex::meshSculptEngine
{
    class MeshManipulator
    {
    public:
        ...
        topologyMesh::Mesh* getMesh();
        const topologyMesh::Mesh* getMesh() const;
        ...
    };
}

The code where I want to use the Mesh (SimpleMeshCorrector.cpp):

void SimpleMeshCorrector::smoothBoundaryLoops(float distance)
{
    if (!_boundaryLoops.empty()) {
        Mesh* mesh = getEngine()->getManipulator()->getMesh();
        ...
    }
}

I get the following error:

A value of type "const vortex::topologyMesh::Mesh*" cannot be used to initialize an entity of type "vortex::topologyMesh::Mesh*"

I can use const_cast but I just don't feel that this is the correct way to solve this problem.


Solution

  • Root cause is (as clarified in comments) that getManipulator() returns a const MeshManipulator*. On a const object, only methods declared const can be called. Thus, the const getter is always called and never the non-const version.

    Depending on the context, there are three ways to go on: