Перейти к основному содержимому
eLearner.app
Модуль 4 · Урок 1 из 29/18 в курсе~12 min
Уроки модуля (1/2)

Классы и объекты

Object-Oriented Programming (OOP) is a core paradigm of C++. It allows grouping data and functions into single entities called classes.

A class acts as a blueprint, while an object is a concrete instance of that class.

Basic Syntax of a class

In C++, you use the class keyword. Unlike some other languages, in C++, class definitions must end with a semicolon ;:

Code
#include <iostream>
#include <string>

class Player {
    // By default, all members of a class are private
private:
    std::string name;
    int score = 0;

public:
    // Public methods to access or modify private data
    void setName(std::string newName) {
        name = newName;
    }

    void addScore(int points) {
        score += points;
    }

    void display() {
        std::cout << name << " has " << score << " points!" << std::endl;
    }
};

int main() {
    Player p; // Creating an object of type Player
    p.setName("Marco");
    p.addScore(15);
    p.display();
    return 0;
}

Access Specifiers: public and private

Encapsulation consists of hiding the internal implementation details of an object and exposing only a controlled interface.

C++ manages this control using access specifiers:

  • private: members are only accessible inside member functions of the class itself.
  • private is the default access level for classes.
  • public: members are accessible from anywhere outside the class.

Try it yourself

Упражнение#cpp.m4.l1.e1
Попыток: 0Загрузка…

Define a class named Rectangle with two private integer members: width and height. Add a public method void setDimensions(int w, int h) to set them, and a method int getArea() that returns width * height. In main, create a Rectangle, set its dimensions to 5 and 4, and print the area.

Загрузка редактора…
Показать подсказку

Use the access specifiers `private:`and`public:`. Remember to close the class with a semicolon `;` after the curly brace.

Решение доступно после 3 попыток

Упражнение#cpp.m4.l1.e2
Попыток: 0Загрузка…

Define a class named Counter with a private member count initialized to 0. Add public methods void increment() and int getCount(). In main, create a Counter object, increment it twice, and print the value.

Загрузка редактора…
Показать подсказку

In C++ moderno puoi inizializzare i membri dato direttamente in classe: `int count = 0;`.

Решение доступно после 3 попыток