'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 1:[1]

The problem is that currently the member function getBarFoo cannot be used on const objects of type FooBar.

To solve this problem you should make the member function getBarFoo a const member function by adding const as shown below:

class FooBar
{
  private:
    bool barFoo; 

  public:
    ////////////////////////VVVVV
    const bool& getBarFoo() const //added const here
    { 
      return barFoo;
    }

    void setBarFoo(bool newVal) 
    {
       
      barFoo = newVal;
    }
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anoop Rana