Syntax reference for C++ classes and objects


Glossary of terms

Term Description
member variables keep track of the state inside each object; also called "instance variables" or "fields"; each object has a copy of each member variable
member functions define the behavior inside each object; also called "methods"; each object has a copy of each method; method can interact with data inside the object (i.e., fields)
constructor initializes new objects as they are created; sets the initial state of each new object; often accepts parameters for the initial state of the fields
destructor called when object is deleted by program (i.e., when object falls out of scope); useful if your object needs to free memory as it dies (delete arrays and pointers)
.h file header file containing the interface (declarations)
.cpp file source file containing definitions (method bodies); content of .h files is #included inside .cpp files
const a const reference parameter can't be modified by the function; a const member function can't change the object's state (i.e., can't modify any fields)
#pragma once protection in case multiple .cpp files include the same .h, so that its contents aren't declared twice

Below is an example of a header and cpp file defining a class meant to model a bank account.

BankAccount.h

#pragma once

#include <string>

using namespace std;

class BankAccount {
public:
    BankAccount(string name, double amount);
    void deposit(double depositAmount);
    void withdraw(double withdrawlAmount);
    void transfer(double transferAmount, BankAccount& recipient);
    
    /* These functions are marked const because they don't change the
     * account.
     */
    double getAmount() const;
    string getName() const;

private:
    string name;
    double amount;
};

BankAccount.cpp

#include "BankAccount.h"
#include "error.h"
using namespace std;

BankAccount::BankAccount(string name, double amount) {
    if (amount < 0) {
        error("That is an invalid amount of money!");
    }
    
    this->name = name;
    this->amount = amount;
}

void BankAccount::deposit(double depositAmount) {
    if (depositAmount < 0) {
        error("You can't deposit negative money!");
    }
    amount += depositAmount;
}

void BankAccount::withdraw(double withdrawlAmount) {
    if (withdrawlAmount < 0) {
        error("You can't withdraw negative money!");
    }
    if (withdrawlAmount > amount) {
        error("Sorry, you don't have enough money in your account to do that!");
    }
    amount -= withdrawlAmount;
}

void BankAccount::transfer(double transferAmount, BankAccount& recipient) {
    this->withdraw(transferAmount); // if we don't have enough money, this will error
    recipient.deposit(transferAmount);
}


/* These methods can be marked const because they don't modify the
 * contents of the bank account.
 */

double BankAccount::getAmount() const {
    return amount;
}

string BankAccount::getName() const {
    return name;
}