Understanding Classes - Definition, Creation, and Usage

Lesson Introduction

Hello! Today, we're diving into an exciting topic: Classes in C++. This lesson aims to introduce you to the concept of classes, how to create them, and how to use them in real-life scenarios. By the end of this lesson, you'll understand the definition of classes, how to create a class in C++, and how to use this class in your code. Ready? Let's get started!

Definition of Classes

So, what exactly is a class? In simple terms, a class is like a blueprint or template for creating objects. Just like blueprints describe the structure and behavior of a house, a class describes the attributes (data members) and behaviors (member functions) of objects. To put this in a real-life context, think of a "Car" as a class. It can have attributes like color, brand, and speed. The class is not some specific car, it is rather a description of what is the car, what information we know about the car.

C++
#include <string>

class Car {
public:
    // Attributes
    std::string color;
    std::string brand;
    int speed;
};

Components of a Class

Classes in C++ are made up of attributes and methods. Attributes store information about the object, while methods define what actions the object can perform. We will learn about methods in the next lesson.

Here's our Car class example:

Attributes:

  • string color - the car's color
  • string brand - the car's brand
  • int speed - the car's current speed

Understanding these components is crucial, as it forms the basis of creating and using classes.

Creating a Class

Creating a class in C++ is straightforward. Start with the class keyword, followed by the class name, and then its attributes and methods inside curly braces. Here's our example once again:

#include <iostream>
#include <string>

class Car {
public:
    std::string color;
    std::string brand;
    int speed;
};

Note how we define car attributes the same way we define regular variables, but inside the class. Now this variables are the parts of the class.

Pay attention to two things:

  1. The class declaration always ends with ;
  2. We start the class with public: keyword. It is the access modifier, and we will discuss its meaning and other options in one of the following lessons. By now, always use public:.
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