Defining Long Functions


In all of our previous examples of classes, we have included the actual code for our functions inside the class definition. This is okay for short 1-2 line functions, but once you start getting to long functions, this can get quite cumbersome with class definitions which go on for pages and pages. So, for these longer functions, C++ allows us to define them outside of the class definition.

class Nacho {
  public:
    void Prompt();
  private:
    int num;
};

void Nacho::Prompt() {
  cout << "Would you like that nacho with or without cheese?";
  cin >> num;
  if (num > 10) 
    cout << "Wow, that's a lot of nachos, you must be hungry!";
}

Instead of actually declaring the entire function inside the class definition, we just have a prototype which acts as a placeholder. The actual method definition looks just like any other function, with the added "Nacho::" to indicate which class this Prompt method is for (in case you have two classes with the same method names, this is used to differentiate between the two). Inside the method definition, we can access private variables within a class just as we could when the function was defined in the class definition.


Table of Contents

Constructors | Destructors | Defining Long Functions | Interface vs. Implementation
Exercises