Skip to content
UPEEC

Classes and Objects in C++

Define your own types with data members, member functions and access control.

Easy
Comments 0
class Led {
public:
    explicit Led(int pin) : pin_(pin) { pinMode(pin_, OUTPUT); }
    void on()  { digitalWrite(pin_, HIGH); }
    void off() { digitalWrite(pin_, LOW); }
private:
    int pin_;
};

Led status(13);
status.on();

public members form the interface; private members are hidden implementation (encapsulation). A struct is the same as a class except members are public by default.

Sub-topics (2)

Constructors and Destructors

Constructors set an object up; destructors clean it up automatically when it goes out of scope.

Intermediate♥ 0🔖 0💬 0

Copy and Move Semantics

How objects are copied or transferred — and the rule of three/five.

Advanced♥ 0🔖 0💬 0

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.