Do class functions/variables have to be declared before being used?

Good question; I’ve relied on that feature for years without thinking about it. I looked through several C++ books to find an answer, including Stroustrup’s The C++ Programming Language and The Annotated C++ Reference Manual, but none acknowledge or explain the difference. But, I think I can reason through it.

The reason, I believe, that your example works is that the bodies of your test and printout aren’t truly where they appear in your file. The code

class MyClass {
  void someFun() {
    x = 5;
  }
  int x;
};

…which appears to violate the rule of having to declare variables before you use them, is actually equivalent to:

class MyClass {
  void someFun();
  int x;
};

void MyClass::someFun() {
  x = 5;
}

Once we rewrite it like that, it becomes apparent that the stuff inside your MyClass definition is actually a list of declarations. And those can be in any order. You’re not relying on x until after it’s been declared. I know this to be true because if you were to rewrite the example like so,

void MyClass::someFun() {
  x = 5;
}

class MyClass {
  void someFun();
  int x;
};

…it would no longer compile! So the class definition comes first (with its complete list of members), and then your methods can use any member without regard for the order in which they’re declared in the class.

The last piece of the puzzle is that C++ prohibits declaring any class member outside of the class definition, so once the compiler processes your class definition, it knows the full list of class members. This is stated on p.170 of Stroustrup’s The Annotated C++ Reference Manual: “The member list defines the full set of members of the class. No member can be added elsewhere.”

Thanks for making me investigate this; I learned something new today. 🙂

Leave a Comment