Classes and structs
Classes with members and constructors, struct for plain data, and smart pointers instead of new / delete.
Runs in Zerethon IDE · C++ (GCC 14)
Official C++ documentation ↗
main.cpp
#include <iostream>
#include <memory>
#include <string>
struct Point {
int x = 0;
int y = 0;
};
class Counter {
public:
explicit Counter(int start) : value_(start) {}
int next() { return ++value_; }
int value() const { return value_; }
private:
int value_;
};
int main() {
Point p{3, 4};
std::cout << p.x + p.y << '\n';
Counter c(10);
c.next();
std::cout << c.next() << ' ' << c.value() << '\n';
auto owned = std::make_unique<Counter>(1); // freed automatically
std::cout << owned->next() << '\n';
}
Output
7 12 12 2
structandclassdiffer only in the default access (publicvsprivate).- Mark methods that do not change the object
const. - Use
std::make_unique/std::unique_ptrinstead of rawnewanddelete; the memory is freed when the pointer goes out of scope.