AnyCompiler

Structs and Classes

A struct groups related values together under one named type, with its members accessible directly by name.

#include <iostream>
#include <string>
using namespace std;

struct Person {
    string name;
    int age;
};

int main() {
    Person alice;
    alice.name = "Alice";
    alice.age = 30;
    cout << alice.name << " is " << alice.age << " years old" << endl;
    return 0;
}
Output
Alice is 30 years old

class and constructors

class is identical to struct in every respect except one: a struct's members are public by default, a class's are private by default. A constructor is a special member function, named after the class, that runs automatically whenever an instance is created — it's the natural place to set up a new object's initial state.

#include <iostream>
#include <string>
using namespace std;

class Person {
public:
    string name;
    int age;

    Person(string n, int a) {
        name = n;
        age = a;
    }
};

int main() {
    Person bob("Bob", 25);
    cout << bob.name << " is " << bob.age << " years old" << endl;
    return 0;
}
Output
Bob is 25 years old

Next: constructors and RAII — the single idea that replaces a garbage collector in idiomatic C++.

Practice exercise

Define a struct Book with fields title (string) and price (double). Create a Book with title "Dune" and price 15.0, then print "<title> costs <price>".