C++ OOP

Object-oriented programming in C++ groups data and the functions that act on it into classes you create objects from. Instead of writing code as one long list of instructions, OOP lets you model your program around objects that bundle data and behavior together. C++ was built with OOP in mind, and understanding it unlocks classes, objects, inheritance, and much more. This page introduces the core ideas so the later class lessons make sense.

What is OOP?

Object-Oriented Programming is a style of coding that organizes software into objects. An object groups together related data (called attributes) and the actions that work on that data (called methods). This mirrors how we think about things in the real world, such as a car that has a color and can drive.

Procedural programming, the older style, focuses on writing functions that act on separate data. OOP instead keeps the data and the functions that use it together, which often makes larger programs easier to organize, reuse, and maintain.

Classes and Objects

A class is a blueprint that describes what an object will look like. An object is a concrete thing created from that blueprint. Think of the class as the plan for a house and each object as an actual house built from that plan.

A simple class and object

#include <iostream>
using namespace std;

class Dog {
public:
  string name; // attribute
  void bark() { // method
    cout << name << " says Woof!" << endl;
  }
};

int main() {
  Dog myDog;        // create an object
  myDog.name = "Rex";
  myDog.bark();     // Rex says Woof!
  return 0;
}

The Four Pillars of OOP

OOP is built on four main ideas. You will explore each one in later lessons, but here is a quick overview so you know where you are headed.

  • Encapsulation: keeping data safe inside an object and controlling access to it.
  • Inheritance: creating new classes based on existing ones to reuse code.
  • Polymorphism: letting one action behave differently depending on the object.
  • Abstraction: hiding complex details and showing only what matters.

Multiple objects from one class

#include <iostream>
using namespace std;

class Circle {
public:
  double radius;
  double area() {
    return 3.14159 * radius * radius;
  }
};

int main() {
  Circle small, big;
  small.radius = 2.0;
  big.radius = 5.0;
  cout << "Small area: " << small.area() << endl;
  cout << "Big area: " << big.area() << endl;
  return 0;
}
Note: You do not need to master all four pillars at once. Start by getting comfortable creating classes and objects; the deeper concepts build naturally on top of that foundation.
TermMeaning
ClassA blueprint for creating objects
ObjectA specific instance of a class
AttributeA variable that belongs to an object
MethodA function that belongs to a class

Exercise: C++ OOP

What does encapsulation in C++ primarily achieve?