Search code examples
c++constants

C++ const parameter directive blocks function use of class


I have a C++ class that is used as a function parameter which is causing me some grief. I can't seem to call function from the class parameter when it is designated as const.

sample class:

class FooBar
{
  private:
    bool barFoo; // I want this modifiable only through functions

  public:
    const bool& getBarFoo() // this function needs to be used to retrieve it
    { 
      return barFoo;
    }

    void setBarFoo(bool newVal) // this is the set function. It validates if the set is possible
    {
      // check if modification is possible. 
      barFoo = newVal
    }
}

I try to use this class in a function similar to this:

void DoShizzle(const FooBar& yesOrNo)
{
  if(yesOrNo.getBarFoo()) // here the code shows an error*
  {
    // do shizzle
  }
  else
  {
    // do other shizzle
  }
}

* the message says 'the object has type qualifiers that are not compatible with the member function "FooBar::getBarFoo" object type is: const FooBar'.

If I remove the 'const' directive from the FooBar parameter in the DoShizzle function, the error goes away. However I read that you should try to tell developers and the compiler what you're doing. I want to keep the variable barFoo private so that it can only be modified using the setBarFoo function, to prevent it being modified without validating if it can be. But I also want to communicate that the function DoShizzle will not edit the FooBar class.

What can is a good solution to my problem? Live with the fact I can't use const here? Or am i missing another solution to my problem? I'm fairly new to C++ and a C# developer by nature so I know I might have to unlearn some practices


Solution

  • const qualifier of a member function is not necessarily the same as the const qualifier of its return type. Actually they are unrelated in general (only when you return a reference to a member, from a const method one can only get a const reference). Your method:

    const bool& getBarFoo() // this function needs to be used to retrieve it
    { 
      return barFoo;
    }
    

    Is a non-const method that returns a const bool& (a constant reference to a bool).

    If you want to be able to call the method on a const FooBar you must declare the method as const:

    const bool& getBarFoo() const // <--------
    { 
      return barFoo;
    }