← Back to C++ Course | Chapter 8: OOP Core | Lesson 2 of 14

C++ Classes & Objects

Defining a Class

A class is a user-defined blueprint that groups member variables (to store data) and member functions (to perform operations) under a single custom type name. Once defined, a class becomes just as usable as any built-in type when declaring new variables.

Example: Defining a Class

cpp
#include <iostream>
#include <string>

class Person {
public:
	std::string name;
	void greet() { std::cout << "Hi, I'm " << name << std::endl; }
};

int main() {
	Person p;
	p.name = "Alex";
	p.greet();
	return 0;
}

Creating Objects

An object is a concrete instance of a class, and you can create one on the stack just like a normal variable, or dynamically on the heap using the new operator. Each object gets its own copy of the class's member variables, independent of every other instance.

Example: Creating Objects

cpp
#include <iostream>
#include <string>

class Person {
public:
	std::string name = "Guest";
};

int main() {
	Person p1;                 // on the stack
	Person *p2 = new Person();  // on the heap
	std::cout << p1.name << " " << p2->name << std::endl;
	delete p2;
	return 0;
}

Class Methods

Methods can be defined directly inside the class body for convenience on short functions, or declared inside the class and defined outside it using the scope resolution operator (::) to keep longer implementations out of the class declaration and easier to read.

Example: Class Methods

cpp
#include <iostream>

class Box {
public:
	int getWidth() { return 5; } // defined inline
	int getHeight();             // declared here, defined below
};

int Box::getHeight() {
	return 10;
}

int main() {
	Box b;
	std::cout << b.getWidth() << " " << b.getHeight() << std::endl;
	return 0;
}

Member Initialization

You can assign default values directly to member variables inside the class definition, which guarantees every newly created object starts in a predictable, valid state even if the constructor doesn't explicitly set every field.

Example: Member Initialization

cpp
#include <iostream>

class Account {
public:
	double balance = 0.0; // default value guarantees consistent starting state
};

int main() {
	Account acc;
	std::cout << acc.balance << std::endl;
	return 0;
}

Arrays of Objects

You can create arrays of objects just like arrays of built-in types, which lets you manage many object instances at once — for example iterating over a fleet of Vehicle objects in a loop instead of declaring each one as a separate named variable.

Example: Arrays of Objects

cpp
#include <iostream>

class Point {
public:
	int x = 0;
};

int main() {
	Point points[3];
	points[1].x = 5;
	std::cout << points[1].x << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.