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 ;:
#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.privateis the default access level for classes.public: members are accessible from anywhere outside the class.
Try it yourself
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.
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
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.
Show hint
In C++ moderno puoi inizializzare i membri dato direttamente in classe: `int count = 0;`.
Solution available after 3 attempts