Skip to main content

Section 16.10 Defining Functions Outside of the Class

We previously learned that we can declare functions (provide the prototype) in one place and define them (write their full bodies) elsewhere. Doing so allows:
  • Us to define functions in any order we want (as long as we declare them first).
  • Create a list of the available functions without wading into the implementation details.
  • Satisfy the demands of the C++ compiler when breaking code into multiple files.
However, if we try to separate definitions of member functions from their declarations, we will run into an issue. Here is a failed attempt to move the Point constructor’s definition outside of the class:
Listing 16.10.1.
Attempting to build the code fails. The compiler has no idea what line 11 is doing. It looks like a function called β€œPoint” that has no return type. And in that function, we use variables m_x and m_y without ever declaring them. There are similar issues with the getX function.
What the compiler needs is a hint that these functions are members of the class Point. We do that by adding the class name and the scope resolution operator :: to the function definitions. Saying Point::getX says β€œThis is the getX that belongs to Point.” And saying Point::Point says β€œThis is the constructors that belongs to Point.” Here is a working version of the code:
Listing 16.10.2.

Insight 16.10.1.

Any time you want to define a function outside of the class declaration, you need to use the scope resolution operator.

Checkpoint 16.10.1.

When should you use the scope resolution operator ::?
  • Any time you define a member function.
  • Incorrect! The scope resolution operator is not always necessary!
  • When you implement member functions inside of the class definition.
  • Incorrect! When you write member functions inside of the class definition, you do not need to specify the scope.
  • When you implement member functions outside of the class definition.
  • Correct! When you write member functions outside of the class definition, you need to specify the scope, hence the :: operator!
  • Never! It is bad practice!
  • Incorrect! The scope resolution operator is good practice when used correctly!

Checkpoint 16.10.2.

What is the correct way to define a member function called string getEmail(); outside the class definition?
  • string Student::getEmail()
  • Student::string getEmail()
  • string is not a member of Student, it is the return type of the function.
  • Student::string Student::getEmail()
  • string is not a member of Student, it is the return type of the function.
  • Student { string getEmail() }
  • We use the :: operator when referring to a member function outside the class. The {} brackets are not used in this case.
You have attempted of activities on this page.