Skip to main content
eLearner.app
Module 4 · Lesson 1 of 29/18 in the course~12 min
Module lessons (1/2)

Classes and Objects

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

Exercise#cpp.m4.l1.e1
Attempts: 0Loading…

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.

Loading editor…
Show hint

Usa gli access specifier `private:`e`public:`. Ricorda di chiudere la classe con un punto e virgola `;` dopo la parentesi graffa.

Solution available after 3 attempts

Exercise#cpp.m4.l1.e2
Attempts: 0Loading…

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.

Loading editor…
Show hint

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

Solution available after 3 attempts