C++ Classes Refresher

Lesson Overview

Greetings! Today, we're revisiting C++ classes, the core building block of Object-Oriented Programming (OOP) in C++. Through hands-on examples, we'll revisit the fundamental concepts of C++ classes, including their structure, attributes, and methods.

C++ Classes Refresher

Let's begin with a refresher on C++ classes. Essential to OOP, C++ classes bundle relevant data and functions into compact units called objects. Consider a video game character, which is a typical example of a class instance, with specific attributes (such as health or strength) and methods (such as attack or defense).

C++
#include <iostream>
#include <string>

class GameCharacter {
public:
    // Constructor
    GameCharacter(std::string name, int health, int strength)
        : name(name), health(health), strength(strength) {}

    // Method
    void attack(GameCharacter& other_character) {
        other_character.health -= this->strength;
    }

    // Attributes
    std::string name;
    int health;
    int strength;
};

C++ classes facilitate the grouping of associated code elements, simplifying their management. Now, to better remind ourselves how the above example works, let's go through it step-by-step.

Structure of a C++ Class

A C++ class serves as a blueprint consisting of attributes and methods. While attributes represent data relevant to a class instance, methods are actions or functions that manipulate this data. Each class includes a constructor, which is used to define class attributes.

An essential keyword within these methods is this, which represents the class instance. In object-oriented programming, it is needed to access the class's attributes and methods. When a new class instance is created, C++ automatically provides access to the instance through the this pointer, allowing each object to keep track of its own state and behaviors.

#include <iostream>
#include <string>

class GameCharacter {
public:
    // Constructor
    GameCharacter(std::string name, int health, int strength)
        : name(name), health(health), strength(strength) {}

    // Method
    void attack(GameCharacter& other_character) {
        other_character.health -= this->strength;
    }

    // Attributes
    std::string name;
    int health;
    int strength;
};
GameCharacter character("Hero", 100, 20);  // object or instance of the class
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal