Section4: Syntax


Classes and Objects Syntax

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

class BankAccount {
public: // publically visible
 	
 	BankAccount(string n, double d);
 	void deposit(double amount);
 	void withdraw(double amount);
 	double getBalance() const;

private: // only visible to class
 	string name;
 	double balance;
};

BankAccount.cpp

#include "BankAccount.h"

// constructor
BankAccount::BankAccount(string n, double b) {
	name = n;
	balance = b;
}

void BankAccount::withdraw(double amount) {
	if (balance >= amount) {
		balance -= amount;
	}
}

void BankAccount::deposit(double amount) {
	balance += amount;
}

double BankAccount::getBalance() const {
	return balance;
}