Class (C++)

A class is a blueprint for creating objects that bundle data (member variables) and behavior (member functions) together. It is the foundation of object-oriented programming in C++.

C++

Members are private by default, meaning they can only be accessed from inside the class. Mark members public to expose them to the outside world.

An object made from a class is called an instance. Classes can also include a constructor to set up new objects and a destructor to clean them up.

Syntax

class Name { public: /* members */ };

Examples

C++

#include <iostream>
#include <string>

class Dog {
public:
    std::string name;
    void speak() {
        std::cout << name << " says woof" << std::endl;
    }
};

int main() {
    Dog d;
    d.name = "Rex";
    d.speak();
    return 0;
}

Output:

Rex says woof

Learn it in a lesson

See also

Back to the Dictionary