Why don’t we take all the naming problems and push them somewhere else?

Naming class members can be a mess in C++.

The simplest idea is to name them like any identifier:

class foo {
  private:
    int size;
};

That’s nice, but what if we want to create a size member function? Unfortunately, you can’t have a a member with the same name as a member function, and so we’ll have to change things up:

class foo {
  public:
    int size(); // we could have also used get_size() and left the member alone
  private:
    int m_size;
};

This isn’t too bad (although I much prefer the first version), but it allows subtle bugs to arise (as seen here http://stackoverflow.com/questions/10678559/c-small-typo-causes-unspeakable-pain/10678689 )

class foo {
  public:
    foo(int size) : m_size(m_size) {}
    int size(); // we could have also used get_size() and left the member alone
  private:
    int m_size;
};

m_size isn’t being properly initialized in the constructor! Not a huge problem anymore as newer compilers should be able to catch this.

So, is there a solution to this silliness? Well, sort-of:


namespace actual_class {
  class foo {
    public:
      foo(int size) :size(size) {}
    protected:
      int size;
  };
}
struct foo : actual_class::foo {
  typedef actual_class::foo get;
  foo(int size) : actual_class::foo(size) {} // in C++11 use constructor inheritance instead
  int size() { return get::size; }
};

This takes advantage of derived classes shadowing their base classes. The possible constructor bug can be eliminated with shadowing, and you don’t have to add extra characters to get unique identifiers.

Is it a good solution? Well, it’s probably better to stick to m_, but it’s worthwhile to know.

Advertisements
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s