c++overloading

How does the compiler determine which member functions mutate?


A comment to one of my posts interested me:

Me too. I also give accessors/mutators the same name.

I was wondering about this, because I have always used setBar(int bar) instead of a mutator named the same thing. I want to know: can the compiler determine based on a const identifier what mutates at runtime, or can it use the same function name because it has a parameter?

Will this compile fine:

class Foo
{
   int bar_;

   public:
      int bar() { return bar_; }
      void bar(int bar) { bar_ = bar; }
}

Or do I have to do this (I realize I should be doing this anyways, just run with me on this):

int bar() const { return bar_; }

I don't know which is which. Const correctness is important, so I think I would want the compiler to object to the overloading since one mutates and one does not.

Why does it work this way?


Solution

  • The first thing the compiler looks at is the number and type of parameters you're passing to the function. This resolves the overload on bar before it even needs to look at const-ness.

    If you fail to mark bar() as const, the compiler will inform you of this the first time you attempt to call bar() on a const instance of the object.