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

Time:02-03

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.

CodePudding user response:

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:

  • Use (or write) a method that returns a mutable MeshManipulator*.
  • Copy the const Mesh* to a local, mutable object.
  • Use const_cast<Mesh*> to be able to mutate the object in place. This, however, defeats the purpose of constness. What's more, if the object pointed to was declared const this will result in undefined behavior. So use with care.
  • Related