Object-oriented programming (OOP) is a programming paradigm.

Classes are data types that are like structs, but expand on having only data elements with functions. Objects are instances of classes, instantiated by the declaration of a class variable. Attributes are data within the class (also called instance variables). Methods are functions within the class (also called function members). Data and methods are always accessed through a specific object.

Note that different classes can use the same method names (so long as they’re defined). Objects are instantiated (created) when a variable of the class type is declared (or dynamically allocated).

Why OOP? Allows definition of new data types, and provides better code organisation by grouping together all functions that access class data.

Key concepts

Four pillars of OOP

Encapsulation, abstraction, inheritance, and polymorphism.

Definition

In C++, we define (maybe in a header file called Person.h ):

class person {
	private:
		string name;
		int age;
	public:
		void setName(string);
		void setAge (int);
		string getName();
		int getAge();
};
 
int main () {
	person x, y;
	person *pp;
	x.setName("Judy");
	pp = new person; // dynamically allocates
	pp->setName("John");
}

Observe how the data are private members. This turns out to be good programming practice! To not have outside methods access of change the data within a class is fairly useful, and called encapsulation.

The definition doesn’t use any memory! Like how the blueprint of the house doesn’t take up any land. But when we use the blueprint, i.e., we build the house, we actually use the land.

Implementation

Within person.cpp, we can implement methods:

type class_name :: method_name (data_type data_name)

#include "person.h"
 
void Person::setname(string n) {
	name = n;
}

By default, we should be defining our class contents within header files and implementing them in .cpp files. This is cleaner and more readable. See code organisation to see why.