Anonymous
Anonymous

Reputation: 4197

Member function still const if it calls functions that break "constness"?

I'm wondering if a class's member function should be const if it calls other functions that modify its data members. A good example would be a public member function that uses private member functions to do the brunt of the work.

void Foo::Show() const { // Doesn't directly modify data members in this function
    ShowPig(); // One or all of these functions modify data members
    ShowCow();
    ShowBar();
}

Maybe not the best example, but you get the idea.

Upvotes: 2

Views: 415

Answers (5)

Charles Eli Cheese
Charles Eli Cheese

Reputation: 783

Yes, the compiler won't let you, as pointed out. Of course you can do it anyway but if the function needs to be const usually it's a bad idea. If it doesn't need to be const, don't just put it in there for no reason. There's really not much benefit to const and many potential serious problems, you just get forced into it at times.

Upvotes: 0

Igor Zevaka
Igor Zevaka

Reputation: 76500

The compiler should not allow you to do that. Example below.

//MS VC 2008
class Foo
{
  int m_iBar;

  void ThisIsConstFunc() const
  {
    m_iBar = 9; //error C2166: l-value specifies const object
    ThisIsNonConst(); //error C2662: 'Foo::ThisIsNonConst' : cannot convert 'this' pointer from 'const Foo' to 'Foo &'
  }

  void ThisIsNonConst() 
  {
    m_iBar = 9;
  }
};

Upvotes: 6

Dan Olson
Dan Olson

Reputation: 23367

C++ provides the mutable keyword for the rare case that you actually want to allow this. And there are times where it happens, for instance if your function does not change the logical state of the object, but may modify one or more members of the object.

These cases are very rare. In the vast majority of cases you should mark the member function const if neither that function nor any function it calls modifies the state of the object.

Upvotes: 3

GManNickG
GManNickG

Reputation: 503805

If a function calls functions that modify certain data, then it should be said that the function itself modifies data. It just happens to be abstracted.

So no, that function should not be const.

Upvotes: 4

aJ.
aJ.

Reputation: 35450

Any Good compiler does not allow this. You should get the compiler error.

Upvotes: 13

Related Questions