Conventions for accessor methods (getters and setters) in C++

Noarth picture Noarth · Sep 5, 2010 · Viewed 79.1k times · Source

Several questions about accessor methods in C++ have been asked on SO, but none was able satisfy my curiosity on the issue.

I try to avoid accessors whenever possible, because, like Stroustrup and other famous programmers, I consider a class with many of them a sign of bad OO. In C++, I can in most cases add more responsibility to a class or use the friend keyword to avoid them. Yet in some cases, you really need access to specific class members.

There are several possibilities:

1. Don't use accessors at all

We can just make the respective member variables public. This is a no-go in Java, but seems to be OK with the C++ community. However, I'm a bit worried about cases were an explicit copy or a read-only (const) reference to an object should be returned, is that exaggerated?

2. Use Java-style get/set methods

I'm not sure if it's from Java at all, but I mean this:

int getAmount(); // Returns the amount
void setAmount(int amount); // Sets the amount

3. Use objective C-style get/set methods

This is a bit weird, but apparently increasingly common:

int amount(); // Returns the amount
void amount(int amount); // Sets the amount

In order for that to work, you will have to find a different name for your member variable. Some people append an underscore, others prepend "m_". I don't like either.

Which style do you use and why?

Answer

From my perspective as sitting with 4 million lines of C++ code (and that's just one project) from a maintenance perspective I would say:

  • It's ok to not use getters/setters if members are immutable (i.e. const) or simple with no dependencies (like a point class with members X and Y).

  • If member is private only it's also ok to skip getters/setters. I also count members of internal pimpl-classes as private if the .cpp unit is smallish.

  • If member is public or protected (protected is just as bad as public) and non-const, non-simple or has dependencies then use getters/setters.

As a maintenance guy my main reason for wanting to have getters/setters is because then I have a place to put break points / logging / something else.

I prefer the style of alternative 2. as that's more searchable (a key component in writing maintainable code).