Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 171 ยท Object-Oriented Programming

Classes and Objects

Learn to define C++ classes - member variables and functions, creating objects, the dot and arrow operators, struct vs class, and defining member functions outside the class.

A class lets you invent a new type. Once you've defined it, you can create variables of that type, pass them to functions, store them in vectors and return them, exactly as you do with int or std::string. Each such variable is an object: a block of memory holding the class's data, together with the functions that know how to work on it.

In Object-Oriented Programming in C++ you saw why classes matter. This lesson covers the mechanics: how to declare a class, add member variables and member functions, create objects and access their members, how struct and class differ (barely), and how to define member functions outside the class body, which is how real projects split code between header and source files. Constructors get their own lesson next; here, members get their starting values from default member initializers.

Defining a class

A class definition starts with the keyword class, a name, and a body in braces. Inside, you list the members: data members (variables) and member functions. The body ends with a semicolon, which is easy to forget.

C++
class Rectangle {
public:                                  // members below are usable from outside
    double width = 1.0;                  // data members with default values
    double height = 1.0;

    double area() const {                // a member function
        return width * height;
    }
};                                       // <- the semicolon is required

A few points about this definition:

  • public: is an access specifier. Members after it can be used by any code. Members of a class are private by default, which you'll explore in Access Specifiers and Encapsulation. This first example keeps everything public so you can focus on the basics.
  • double width = 1.0; is a default member initializer: every new Rectangle starts with that value. Without it, a double member of a local object would start uninitialized, holding garbage.
  • area() reads width and height directly, without any prefix. Inside a member function, the names of members refer to the members of the object the function was called on.
  • The const after area() promises that the function doesn't modify the object. Mark every member function that only reads data as const; the reason is explained in const Member Functions and mutable.

By convention, class names use PascalCase (Rectangle, BankAccount), while members follow the same style as other variables and functions in your project.

Creating objects and accessing members

Defining a class creates no objects; it's a blueprint. You create objects like any other variable, and you reach their members with the dot operator .. Every object has its own copy of each data member, so changing one object leaves the others alone.

C++ Objects have their own data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

When you write b.area(), the function runs with width and height meaning b.width and b.height. Behind the scenes, the compiler passes the address of b as a hidden argument named this; you'll see it explicitly in The this Pointer.

Pointers to objects and the arrow operator

When you have a pointer to an object, use the arrow operator -> instead of the dot. p->area() means exactly (*p).area(); the arrow just saves you the parentheses. You'll use it most with smart pointers and with objects stored on the heap.

C++ The dot and arrow operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The rule is simple: object or reference โ†’ dot; pointer (raw or smart) โ†’ arrow.

Member functions

Member functions can do anything a free function can: take parameters, return values, call other functions, and call other member functions of the same object (again without any prefix). They also have privileged access to the object's private members, which is the whole point of encapsulation.

A typical class mixes queries (const functions that report something about the object) and commands (functions that change it). Here is a small playlist with both.

C++ A class with queries and commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

print() calls size(), total_seconds() and format_time() directly, because they're members of the same class. format_time is static: it doesn't need any object's data, so it doesn't receive a this pointer at all (Static Members covers that). Member functions can be declared in any order inside the class: print uses format_time even though it appears later, because the compiler reads the whole class body before compiling member function bodies.

This Playlist still has a design flaw: songs and lengths are public, so outside code could push a song without a length and break the "same size" rule. In Access Specifiers and Encapsulation you'll make them private and let the class enforce that rule.

struct vs class

C++ has two keywords for defining classes, struct and class, and they create exactly the same kind of type. There is only one difference: the default access.

Members are by default Base classes are by default
struct public public
class private private

Everything else is identical: a struct can have member functions, constructors, private sections, inheritance and virtual functions. The choice is about communicating intent, and most C++ code follows this convention:

  • Use struct for simple bundles of data where every member is public and any combination of values is valid: a point, a configuration record, a function's multiple return values.
  • Use class when the type has invariants and hides its data behind member functions.
C++ The only difference is the default access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

PointS c{5, 7} works because PointS is an aggregate: a class with public data and no user-written constructors, which can be initialized member by member with braces. Structs, Aggregates and Unions covers aggregates and C++20 designated initializers such as PointS{.x = 5, .y = 7}.

Defining member functions outside the class

Small member functions are often written inside the class. Larger ones are usually only declared inside, then defined outside using the class name and the scope resolution operator ::. In real projects the class definition goes into a header file and the definitions into a .cpp file, so that other files can include the header without recompiling the function bodies (Header Files and Multiple Source Files).

C++
// temperature_log.h
#pragma once
#include <vector>

class TemperatureLog {
public:
    void record(double celsius);
    double average() const;
    double highest() const;

private:
    std::vector<double> readings_;
};
C++
// temperature_log.cpp
#include "temperature_log.h"
#include <algorithm>

void TemperatureLog::record(double celsius) {
    readings_.push_back(celsius);
}

double TemperatureLog::average() const {        // const must be repeated here
    // ...
}

TemperatureLog::record reads as "the function record that belongs to TemperatureLog". Inside its body you're in the class's scope, so members (even private ones) are available by plain name, just as for functions written inside the class.

Our editor compiles a single file, so the runnable version below keeps everything in one place, but the shape is the same.

C++ Member functions defined outside the class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Rules to remember when splitting declaration and definition:

  • The signature must match exactly, including const. Defining double TemperatureLog::average() without const is an error ("no declaration matches").
  • Default arguments go only in the declaration inside the class, not in the outside definition (Default Arguments).
  • Functions defined inside the class body are implicitly inline, so they may live in a header without breaking the one-definition rule. Functions defined outside the class in a header need the inline keyword (inline Functions).
  • The return type comes before ClassName::, so a return type that is itself a member type needs qualifying too: TemperatureLog::Unit TemperatureLog::unit() const. A trailing return type (auto TemperatureLog::unit() const -> Unit) avoids the repetition.

Objects are values

C++ objects behave like ints, not like references in Java, Python or C#. Assigning one object to another copies every member; passing an object by value to a function copies it; and two objects are never secretly the same object unless you use a reference or pointer.

C++ Copies, references and vectors of objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Copying is safe and predictable for classes made of values like std::string and double. When a class manages a resource itself (a raw pointer to heap memory, a file handle), the default member-by-member copy can be wrong; Copy Constructors and Copy Assignment shows how to handle that. Objects don't get == automatically, but in C++20 one line (= default) asks the compiler to compare all members in order; Operator Overloading explains it fully.

Pass objects to functions the same way as strings and vectors: by const& to read, by & to modify, by value when the function needs its own copy (Parameters).

Common mistakes

  • Forgetting the semicolon after the class's closing brace. The error often appears on the next line, with a confusing message such as "expected ';' after class definition" or a complaint about whatever follows.
  • Writing Rectangle r(); to create an object. This declares a function named r that returns a Rectangle (the "most vexing parse"). Write Rectangle r; or Rectangle r{}; instead.
  • Leaving members uninitialized. struct Stats { int count; double mean; }; makes a local Stats s; hold garbage. Give every member a default value or a constructor that sets it.
  • Using . on a pointer or -> on an object. The compiler error mentions "request for member ... which is of pointer type"; switch to the other operator.
  • Expecting reference semantics. Item copy = pen; is a separate object. Use Item& alias = pen; when you really want a second name for the same object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the only language difference between struct and class?

    Both keywords define the same kind of type. Only the default access differs; you can add any access specifier, member function or base class to either.
  2. 2. Counter a; Counter b = a; b.increment(); If increment adds 1 to value, what happens to a.value?

    C++ objects are values. Initializing b from a copies every member, so b.increment() only affects b.
  3. 3. You have auto shape = std::make_unique<Rectangle>();. How do you call its area function?

    A unique_ptr behaves like a pointer, so you use the arrow operator. (*shape).area() would also work.
  4. 4. A class declares double average() const;. Which outside definition is correct?

    The definition needs the class name and the scope resolution operator before the function name, and the const must be repeated so the signature matches the declaration.
  5. 5. What does Rectangle r(); do inside main?

    This is the most vexing parse. Empty parentheses make it a function declaration. Use Rectangle r; or Rectangle r{}; to create an object.

Summary

  • A class definition lists data members and member functions inside braces and ends with a semicolon. An object is an instance with its own copy of the data.
  • Default member initializers (double width = 1.0;) give every new object a defined starting value.
  • Access members with . on objects and references, and with -> on pointers and smart pointers.
  • Member functions use other members by plain name; mark functions that only read the object as const.
  • struct and class differ only in default access (public vs private). Use struct for plain data and class for types with invariants.
  • Define member functions outside the class with ReturnType ClassName::name(...), repeating const, and keep default arguments in the declaration.
  • Objects are values: assignment and pass-by-value copy them. Use references to share, and = default for member-wise ==.

Next: Constructors and Member Initializer Lists, where you'll control exactly how each object is created.