Free course · Lesson 4 of 5
Pointers, References & Classes
In this lesson you will
- Explain references and pointers
- Write a simple class with private data and member functions
A pointer stores the memory address of a value; a reference is a safer alias for an existing variable. Together with classes (grouping data and behavior, just like in Java or Python), these are what set C++ apart from higher-level languages.
int* p = &x;—pholds the address ofx;*preads its value.void increment(int& x)— a reference parameter lets a function modify the caller's variable directly.- A
classbundles data (fields) and behavior (methods) into one type, same idea as Java/Python. - Modern C++ prefers smart pointers (
std::unique_ptr) over rawnew/delete— covered at the Advanced level.
💡 Practical Skill: Understanding what a pointer actually points to — before writing one — prevents the majority of C++ crashes beginners run into.
#include <iostream>#include <string> class Car {public: std::string brand; Car(std::string b) : brand(b) {} // constructor void honk() { std::cout << brand << " says: Beep beep!" << std::endl; }}; void addYear(int& age) { // reference: modifies the caller's variable age = age + 1;} int main() { Car myCar("Toyota"); myCar.honk(); // Toyota says: Beep beep! int carAge = 3; addYear(carAge); std::cout << "Car age next year: " << carAge << std::endl; // 4 return 0;}
Practice exercise
Write a Battery class with a charge level from 0 to 100 and member functions to use and charge it, rejecting values outside the range.
Key takeaways
- A reference is another name for an existing object
- A pointer holds an address and may be nullptr — check before using it
- Classes keep data private and enforce rules in member functions
Free self-study lesson — no certificate. For the full instructor-led program, see registration options.