Table of Contents

1. Functions

1.1. Function headers

A function header contains the following information:

RETURNTYPE FUNCTIONNAME( PARAMETERLIST )

  • The return type is the type of data returned (like an int), or void for functions that don't need to return any data.
  • The function name follows the same naming rules as a variable - letters, numbers, and underscores allowed, no spaces or other special characters.
  • The parameter list is a series of variable declarations to be used within the function. These parameters are assigned values during the function call, when arguments are provided.

1.2. Function declarations

Function declarations should go in .h files. A function declaration is the function header, with a semicolon at the end:

int Sum( int a, int b );
void DisplayMenu();

1.3. Function definitions

Function definitions should go in .cpp files. A function definition is the function header, plus a code block, starting and ending with curly braces {}:

int Sum( int a, int b )
{
  int result = a + b;
  return result;
}

1.4. Function calls

Function calls will happen within other functions. A function call includes the function's name, input arguments to be passed in, and the return data will need to be stored in a variable, if applicable.

int num1, num2, result;
cout << "Enter two numbers, separated by a space: ";
cin >> num1 >> num2;
result = Sum( num1, num2 ); // Function call
cout << "Result: " << result << endl;

1.5. Header files

  • Function declarations should go in header files (.h files).
  • Header files must have file guards, this prevents the .h file from being "copied" into multiple files, which will cause a "duplicate code" build error.
  • For the file guard, a label like _FILENAME_H is used. This must be unique for each file!
  • Visual Studio supports using #pragma once for .h files, but this is not cross platform, so you should use these preprocessor file guards!
  • Example file guard for a .h file:

    #ifndef _FILENAME_H
    #define _FILENAME_H
    
    // Code goes here
    
    #endif
    

1.6. Source files

  • Function definitions should go in source files (.cpp files). File guards are not put in .cpp files.

1.7. Using your functions in other files

  • Any file that utilizes your function must include the .h file:

    #include "MyFunctions.h"
    
  • Note that something like #include <iostream> is used for including libraries that are not inside the project. Using "" is for including files that are in your project.
  • NEVER INCLUDE .cpp FILES, THIS WILL GENERATE ERRORS!

1.8. Function overloading

  • Multiple functions can have the same name as long as their function signatures are different. This means that two functions with the same name either need a different number of parameters, or different parameter data types, so that they can be unambiguously identified.
  • AMBIGUOUS:

    void MyFunction( int a, int b );
    void MyFunction( int num1, int num2 );
    
  • UNAMBIGUOUS:

    void MyFunction( int num1, int num2 );
    void MyFunction( string name1, string name2 );
    void MyFunction( int oneNum );
    

2. Structs and classes

2.1. Accessibility levels

  • We can specify accessibility levels for struct and class members. This information dictates where a struct/class' internal contents can be accessed from:
Accessibility level Class' functions? Child's functions? External functions?
private Yes NO NO
protected Yes Yes NO
public Yes Yes Yes
  • private members can only be accessed from the class' own functions.
  • protected members can only be accessed from the class' own functions, and also the functions of any other classes that INHERIT from this class.
  • public members can be accessed from anywhere in the program, including functions that are not a part of the class.

2.2. Structs

  • Structs are usually used to store very basic structures, often with just variable data and no functions.

    struct Coordinate
    {
      float x, y;
    };
    
  • Struct declarations should go in their own .h file, usually the filename will match the name of the class, such as "Coordinate.h".
  • All .h files need file guards!
  • Also note that at the closing curly brace } of the struct declaration there is a semicolon - this is required!
  • Members of a struct are public level accessibility by default.

2.3. Classes

  • Classes are meant for more complex structures.

    class CLASSNAME
    {
        public:
        // Public members
    
        protected:
        // Protected members
    
        private:
        // Private members
    };
    
  • Class declarations should go in their own .h file, and class function definitions should go in a corresponding .cpp file!
  • It is best practice to make member variables of a class private, and only provide indirect access to this data via functions.
  • Example: Product.h

    #ifndef _PRODUCT_H  // File guards
    #define _PRODUCT_H  // File guards
    
    #include <string>
    using namespace std;
    
    class Product
    {
        public:
        // Constructors:
        Product();
        Product( string newName, float newPrice );
    
        // Destructor:
        ~Product();
    
        // Setters:
        void SetName( string newName );
        void SetPrice( float newPrice );
    
        // Getters:
        string GetName() const;
        float GetPrice() const;
    
        private:
        string m_name;
        float m_price;
    }
    
    #endif
    
  • Example: Product.cpp

    #include "Product.h"
    
    // Constructors:
    Product::Product()
    {
      m_name = "unset";
      m_price = 0;
    }
    
    Product::Product( string newName, float newPrice )
    {
      SetName( newName );
      SetPrice( newPrice );
    }
    
    // Destructor:
    Product::~Product()
    {
      cout << "Bye." << endl;
    }
    
    // Setters:
    void Product::SetName( string newName )
    {
      m_name = newName;
    }
    
    void Product::SetPrice( float newPrice )
    {
      if ( newPrice >= 0 )
      {
        m_price = newPrice;
      }
    }
    
    // Getters:
    string Product::GetName() const
    {
      return m_name;
    }
    
    float Product::GetPrice() const
    {
      return m_price;
    }
    
  • Accessor/Getter functions:
    • Don't take in any input data (no parameters).
    • Return the value of a private member variable (has a return).
    • Should be marked const to prevent data from changing within the function. (This is "read only")
  • Mutator/Setter functions:
    • Take in an input value of the new data to be stored (has a parameter).
    • Generally doesn't return any data (no return, void return type).
  • Constructor functions:
    • Called automatically when a new object of that class type is created.
    • Can overload.
  • Destructor functions:
    • Called automatically when an object of that class type is destroyed/loses scope.
    • Cannot overload.

2.4. Class objects / instantiating a class object

  • Once we've declared a class we can then declare variables whose data types are that class:

    PlayerCharacter bario;
    NonPlayerCharacter boomba;
    
  • In this example, bario is a PlayerCharacter object, aka an "instantiation of the PlayerCharacter object".

2.5. Class inheritance

  • A class (called a subclass or a child class) can inherit from another class (called a superclass or a parent class). Doing this means that any protected and public members are inherited by the child class. This can be useful for creating more "specialized" versions of something, storing the shared attributes of a set of items in a common "parent" class.
  • Example:

    class Character
    {
      void SetPosition( float x, float y );
      void Move( float xAmount, float yAmount );
    
      protected:
      float x, y;
    };
    
    class PlayerCharacter : Public Character
    {
      public:
      void GetKeyboardInput();
    
      private:
      int totalLives;
    };
    
    class NonPlayerCharacter : public Character
    {
      public:
      void ComputerDecideMove();
    
      private:
      bool attackPlayer;
    };
    

2.6. Class composition

  • Class composition is where a class contains class objects as member variables. This is another form of object oriented design where a class might "contain" traits that could be inherited, but instead encapsulates them into a sub-object.
  • Example:

    class MovableObject
    {
      void SetPosition( float x, float y );
      void Move( float xAmount, float yAmount );
    
      private:
      float x, y;
    };
    
    class PlayerCharacter
    {
      public:
      void GetKeyboardInput();
    
      private:
      int totalLives;
      MovableObject mover;
    };
    

Author: RachelWil

Created: 2026-10-14 Wed 11:11

Validate