Skip to content

Instantly share code, notes, and snippets.

@skiadas
Last active January 19, 2020 22:17
Show Gist options
  • Save skiadas/f8fdf8bf99482eeea8b86c48544186b3 to your computer and use it in GitHub Desktop.
Save skiadas/f8fdf8bf99482eeea8b86c48544186b3 to your computer and use it in GitHub Desktop.

Classes in C++

  • objects contain:
    • data in the form of member variables (also called instance variables).
    • as well as the functions we can use to interact with that data, in the form of member functions.
  • objects allow us to provide information hiding.
    • We cannot see and interact with the private members of an object.
    • We can only use the public member functions.
  • A class is a blueprint for objects (technically a bit more).
    • Name and type of the member variables.
    • Function prototypes for the member methods.
    • Implementations for the member methods.
    • Details on how to create objects (constructors).
    • BUT: each object has its own copies of the member variables.
  • Two kinds of member functions:
    • modification member functions can change the object's values.
    • constant member functions cannot change the object's values.
  • A class also provides a new type:
    • We can declare a variable of type the class.
    • We can pass objects of that arguments to functions.
  • Declaring variables of a class: Always creates an object.
    • foo a; stores in a an object of class foo, by calling the default constructor.
    • foo a(5); stores in a an object of class foo, by calling an appropriate parametrized constructor.
    • foo a(b); where b is an object of class foo, uses the copy constructor to create a copy of the object in b and store it in a.
  • Constructor syntax:
    • Same name as the class.
    • No return type.

Class syntax

// CLASS DECLARATION
// BIG COMMENT HERE
class throttle {
  public:
    // CONSTRUCTOR PROTOTYPES
    ...
    // MEMBER FUNCTION PROTOTYPES
    void shut_off();
    ...
  private:
    // MEMBER VARIABLES
    ...
};                 //  <---------- DONT FORGET THE SEMICOLON!!

// MEMBER FUNCTION IMPLEMENTATIONS COME LATER
void throttle::shut_off() {
  ...
}

Code organization

  • Header files
    • extension .h
    • contains the parts other sections of the program need to know about
    • class definitions
    • class comment
    • macro guard to allow for multiple include without problems
    • never use using namespace ...
  • Implementation files
    • extension .cpp
    • contains implementation of class methods
    • contains other helper methods and variables
    • include the header file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment