Order Matters Inside of C++ Classes

Confession time: I’ve been putting some effort into learning C++, after years of swearing I’d stick with straight C. The push to C++ has been driven by SFML, which I’d really like to play with. The SFML documentation and samples are really good, and have convinced me that maybe C++ isn’t all bad. I’m having some success, but I’ve run into tons of obvious-in-hindsight rules.

It’s common to see C++ classes declare all of the public members first, and the private members second, but you can’t always do that. Order matters. This won’t work:


class StructDemo
{
public:
 StructDemo(void);
 struct example FillStruct();

private:
 struct example
 {
  int x;
  float y;
  bool z;
 } example;
};

struct StructDemo::example StructDemo::FillStruct()
{
 struct StructDemo::example test;
 test.x = 1; test.y = 2; test.z = 1;
 return test;
}

Visual Studio gives me a heads up that my definition of StructDemo::FillStruct() doesn’t match the function prototype in the class, and it won’t compile without error.

structerror

After some Googling I found a relevant Stack Overflow question about it: http://stackoverflow.com/questions/5523109/c-define-class-member-struct-and-return-it-in-a-member-function

Ah – of course order matters! My problem came from thinking that public variables/methods had to come before private. It’s not the case. This is valid, and makes complete sense in hindsight. You have to declare variables before you can use them. Obviously!


class StructDemo
{
private:
 struct example
 {
  int x;
  float y;
  bool z;
 } example;

public:
 StructDemo(void);
 struct example FillStruct();
};

I can see many more posts coming up about the bonehead things I do out of superstitious cargo cult thinking.

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