Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Grouping values with struct
    4. Naming each value: designated initializers
    5. Member functions
    6. const member functions
    7. this: the object a function was called on
    8. public and private: keeping the rules
    9. struct or class?
    10. static members: one per type
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. Forgetting the ; after the closing brace
    15. Leaving out a member when you initialize
    16. Try it yourself

    Module 4 · Your own types

    4.1Structs and classes

    Group related values into a type of your own with struct, give it member functions, and use private members so the rest of the program can't break its rules.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Grouping values with struct
    4. Naming each value: designated initializers
    5. Member functions
    6. const member functions
    7. this: the object a function was called on
    8. public and private: keeping the rules
    9. struct or class?
    10. static members: one per type
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. Forgetting the ; after the closing brace
    15. Leaving out a member when you initialize
    16. Try it yourself

    Key terms

    struct
    A type you define yourself, made of named members. Its members are public unless you say otherwise.
    class
    The same as a struct, except its members are private unless you say otherwise.
    member
    A named part of a struct or class: a data member is a value stored in every object, like quality in a Read; a member function is a function you call on an object with ..
    aggregate initialization
    Creating a plain struct by listing its members' values in braces, in the order they're declared: Read r{"r1", "ACGT", 30};.
    designated initializer
    Naming each member in braces as you set it: Read r{.id = "r1", .bases = "ACGT", .quality = 30};.
    const member function
    A member function with const after its parameter list. It promises not to change the object, so you can call it on a const object or through a const&.
    this
    Inside a member function, a pointer to the object the function was called on.
    access specifier
    public: or private: inside a struct or class. Members after public: can be used by any code; members after private:, only by the type's own member functions.
    invariant
    A rule about an object's data that must always hold, like "the bases are only A, C, G or T".
    static member
    A member that belongs to the type itself, not to each object. You use it as Type::name, and there is one copy for the whole program.

    So far you’ve mostly used the types C++ gives you, like int, std::string and std::vector, plus a few tiny structs: Probe in Stack, heap and lifetime and Buffer in Dynamic memory and RAII. A sequencing read has an ID, its bases and a quality score. Keeping those in three separate variables, and passing all three to every function, gets old fast. A struct puts them in one type, gives that type its own functions, and can keep its data safe from the rest of the program.

    In 30 seconds

    • struct Read { std::string id; std::string bases; int quality; }; defines a new type. Every Read object holds those three data members.
    • Functions declared inside the struct are member functions: read.length(). Mark the ones that only read with const.
    • Members after private: can only be used by the type’s own member functions. That lets a type keep its invariant, a rule about its data that must always hold.
    • struct and class are the same thing, except a struct’s members are public unless you say otherwise, and a class’s are private.

    Grouping values with struct

    A struct definition lists its members, each with a type and a name, between braces. Note the ; after the closing brace. Once it’s defined, Read is a type like any other: you create objects of it, and reach a member with ..

    #include <print>
    #include <string>
    
    struct Read {
        std::string id;
        std::string bases;
        int quality;
    };
    
    int main() {
        Read read{"r1", "ACGTTG", 31};
        read.quality += 2;
        std::println("{} {} {}", read.id, read.bases, read.quality);
    }

    Output

    r1 ACGTTG 33

    Read read{"r1", "ACGTTG", 31}; is aggregate initialization: the values in the braces go to the members in the order they’re declared. It works for a plain struct like this one, whose members are all public and which has no constructors (the next lesson covers constructors).

    Naming each value: designated initializers

    With three members of similar types, it’s easy to put values in the wrong order. Designated initializers name each member as you set it. The names must come in the order the members are declared. Empty braces set every member to zero, or to empty for a std::string:

    #include <print>
    #include <string>
    
    struct Read {
        std::string id;
        std::string bases;
        int quality;
    };
    
    int main() {
        Read named{.id = "r2", .bases = "GGCA", .quality = 28};
        Read empty{};
        std::println("{} {} {}", named.id, named.bases, named.quality);
        std::println("[{}] [{}] {}", empty.id, empty.bases, empty.quality);
    }

    Output

    r2 GGCA 28
    [] [] 0

    A struct is a type, so everything you know works with it: a std::vector<Read>, a function that takes a const Read&, a function that returns a Read.

    Member functions

    A function declared inside the struct is a member function. You call it on an object, with ., and inside it the object’s members are available by name: bases means the bases of the object the function was called on.

    #include <print>
    #include <string>
    
    struct Read {
        std::string id;
        std::string bases;
        int quality;
    
        std::size_t length() const { return bases.size(); }
        bool passes(int min_quality) const { return quality >= min_quality; }
    };
    
    int main() {
        Read good{"r1", "ACGTTG", 33};
        Read poor{"r2", "AC", 12};
        std::println("{}: {} bases, passes {}", good.id, good.length(),
                     good.passes(20));
        std::println("{}: {} bases, passes {}", poor.id, poor.length(),
                     poor.passes(20));
    }

    Output

    r1: 6 bases, passes true
    r2: 2 bases, passes false

    const member functions

    The const after length() and passes(int) is a promise: this function doesn’t change the object. The compiler holds the function to it, so assigning to a member inside it is a compile error. In return, you can call it on a const object or through a const Read&.

    That matters because functions usually take big objects by const reference, as References showed. Leave the const off, and such a function can’t call it:

    #include <print>
    #include <string>
    
    struct Read {
        std::string id;
        int quality;
    
        bool passes(int min_quality) { return quality >= min_quality; }
    };
    
    void report(const Read& read) {
        std::println("{}: {}", read.id, read.passes(20));
    }
    
    int main() {
        report(Read{"r1", 33});
    }

    The compiler rejects this

    main.cpp: In function ‘void report(const Read&)’:
    main.cpp:12:48: error: passing ‘const Read’ as ‘this’ argument discards qualifiers [-fpermissive]
       12 |     std::println("{}: {}", read.id, read.passes(20));
          |                                     ~~~~~~~~~~~^~~~
    main.cpp:8:10: note:   in call to ‘bool Read::passes(int)’
        8 |     bool passes(int min_quality) { return quality >= min_quality; }
          |          ^~~~~~

    GCC says passing a const Read as the this argument “discards qualifiers”: calling passes would drop the const. Clang says plainly that the function is not marked const. The fix is to add const after the parameter list: bool passes(int min_quality) const.

    Key ideaMake every read-only member function const

    If a member function doesn’t change the object, mark it const. Code that holds a const T& can then call it. Leave const off only for functions whose job is to change the object.

    this: the object a function was called on

    Inside a member function, this is a pointer to the object the function was called on. For good.length(), this points at good. You rarely need to write it, because bases already means this->bases (-> reaches a member through a pointer, as in Pointers). Two cases where you do: when a parameter has the same name as a member, and when you need the object’s address.

    #include <print>
    #include <string>
    
    struct Read {
        std::string id;
        int quality;
    
        void set_quality(int quality) { this->quality = quality; }
        bool is(const Read& other) const { return this == &other; }
    };
    
    int main() {
        Read a{"r1", 20};
        Read b{"r2", 20};
        a.set_quality(35);
        std::println("{} {}", a.quality, b.quality);
        std::println("{} {}", a.is(a), a.is(b));
    }

    Output

    35 20
    true false

    In set_quality, plain quality means the parameter, so this->quality names the member. In a const member function, this is a pointer to a const Read. That’s how the compiler stops a const function from changing members.

    public and private: keeping the rules

    A read’s bases should only be A, C, G or T. With a plain struct, any line of the program can write read.bases = "HELLO", and every function that uses the bases has to check them again. Access specifiers fix this. Members after private: can only be used by the type’s own member functions; members after public: can be used by anyone. The rule that the bases are always valid is the type’s invariant, and only the type’s own code can break it.

    #include <print>
    #include <string>
    
    class Sequence {
    public:
        bool append(char base) {
            if (base != 'A' && base != 'C' && base != 'G' && base != 'T') {
                return false;
            }
            bases_ += base;
            return true;
        }
        const std::string& bases() const { return bases_; }
    
    private:
        std::string bases_;
    };
    
    int main() {
        Sequence seq;
        seq.append('A');
        seq.append('C');
        bool added = seq.append('X');
        seq.append('G');
        std::println("{} {}", seq.bases(), added);
    }

    Output

    ACG false

    append is the only way to add a base, and it refuses anything else. bases() returns a const reference to the text, so callers can read it without a copy but can’t change it through it. The _ at the end of bases_ isn’t required; it’s a common way to mark private data members and to keep the name bases free for the function. Sequence seq; starts with an empty bases_, because a std::string starts empty.

    Code outside the class that touches a private member doesn’t compile:

    #include <string>
    
    class Sequence {
    public:
        const std::string& bases() const { return bases_; }
    
    private:
        std::string bases_;
    };
    
    int main() {
        Sequence seq;
        seq.bases_ = "HELLO";
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:13:9: error: ‘std::string Sequence::bases_’ is private within this context
       13 |     seq.bases_ = "HELLO";
          |         ^~~~~~
    main.cpp:8:17: note: declared private here
        8 |     std::string bases_;
          |                 ^~~~~~

    The fix is to go through the public functions, like append. If outside code really needs to set the bases directly, the type has no invariant to protect, and a plain struct is the better choice.

    struct or class?

    Sequence above is written with class. The keywords struct and class make exactly the same kind of type. The only difference is the default access: a struct’s members are public until you write private:, and a class’s are private until you write public:. (The default also differs for inheritance, which Inheritance and virtual functions covers.)

    Most C++ code follows a convention:

    • struct for plain data with no rules to protect, where every member is public: Read, a point, a pixel.
    • class for a type with an invariant, with private data and public member functions: Sequence.

    static members: one per type

    A member marked static belongs to the type itself, not to any one object. A static member function has no this, so it can’t use an object’s data members; a static data member is stored once for the whole program. You reach either with the type’s name and ::, the scope resolution operator, as std::println is the println in std:

    #include <cstddef>
    #include <print>
    
    class Sequence {
    public:
        static constexpr std::size_t max_length = 150;
    
        static bool is_base(char c) {
            return c == 'A' || c == 'C' || c == 'G' || c == 'T';
        }
    };
    
    int main() {
        std::println("{} {}", Sequence::is_base('G'), Sequence::is_base('N'));
        std::println("{}", Sequence::max_length);
    }

    Output

    true false
    150

    static constexpr makes a constant that belongs to the type, like the longest read Sequence accepts. is_base doesn’t need an object, so it’s static; append could call it instead of repeating the check.

    Which one should I use?

    WhatWhenWhyHow
    A plain structValues that belong together, with no rule linking them: a read, a point, a hit in a search.Aggregate and designated initialization work, and code reads the members directly.struct Hit { int position; float score; };
    A class with private membersThe data has an invariant: valid bases only, a count that matches a list.Only the class’s own functions can change the data, so the rule can’t be broken from outside.class Sequence { public: … private: … };
    A member functionThe function needs the object’s private members, or it’s clearly an action of the type.It’s called as seq.append('A'), and it can reach private members.bool append(char base);
    A free functionIt only needs the public members.The type stays small, and the function is easy to find and test alone.double gc_fraction(const Read& read);
    A static memberA constant or a helper that belongs to the type but not to one object.One copy, named by the type.static bool is_base(char c);

    Rule of thumb: start with a plain struct. Switch to a class with private data the moment there’s a rule the data must follow.

    Under the hood

    An object of a struct is its data members, stored one after another in the order they’re declared. Member functions aren’t stored in the object: the compiler turns each one into an ordinary function with a hidden first parameter, the this pointer. For a Call object c, c.passes() becomes, roughly, a call to passes with &c as its first argument. static members aren’t stored in the object either.

    #include <cstddef>
    #include <print>
    
    struct Call {
        char base;
        float quality;
        int position;
    
        static constexpr float min_quality = 20.0f;
        bool passes() const { return quality >= min_quality; }
    };
    
    
    int main() {
        std::println("{} {} {}", sizeof(char), sizeof(float), sizeof(int));
        std::println("{}", sizeof(Call));
    }

    Output

    1 4 4
    12

    The members add up to 9 bytes, but a Call is 12 here. The compiler put 3 bytes of padding after base, so that quality starts at an address that’s a multiple of 4, which is what a float needs on this platform. passes and min_quality take no room at all.

    A Call object in memory
    A Call object in memory: each row is one value; each cell's width is its size in bytes.
    Value01234567891011Size
    Callbase1 bytepadding3 bytesquality4 bytesposition4 bytes12 bytes

    A Call is 12 bytes on this platform: base takes byte 0, bytes 1 to 3 are padding, quality takes bytes 4 to 7 and position takes bytes 8 to 11. The member function passes and the static member min_quality are not stored in the object.

    offsetof(Call, quality), from <cstddef>, gives the byte where a member starts; this page checks it’s 4. Module 9 covers padding and alignment, and how ordering members can shrink a struct.

    PerformanceMember functions cost nothing in the object

    Adding ordinary member functions never makes objects bigger, and calling one costs the same as calling a free function with a pointer argument. (Virtual functions, in Inheritance and virtual functions, add one hidden pointer to each object.) Whether you write read.length() or length(read) is about design, not speed.

    Common pitfalls

    Forgetting the ; after the closing brace

    A struct or class definition ends with };, unlike a function. Leave out the ; and the compiler reads the next line as part of the same declaration:

    struct Read {
        int quality;
    }
    
    int main() {
        Read read{30};
    }

    The compiler rejects this

    main.cpp:3:2: error: expected ‘;’ after struct definition
        3 | }
          |  ^
          |  ;

    The message points at the closing brace and shows where the ; goes.

    Leaving out a member when you initialize

    Aggregate initialization with fewer values than members is allowed by the C++ rules: the missing members are set to zero, or empty. But it’s often a mistake, such as forgetting the quality score, so -Wextra warns, and with warnings as errors it doesn’t compile:

    #include <string>
    
    struct Read {
        std::string id;
        std::string bases;
        int quality;
    };
    
    int main() {
        Read read{"r1", "ACGT"};
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:10:27: error: missing initializer for member ‘Read::quality’ [-Werror=missing-field-initializers]
       10 |     Read read{"r1", "ACGT"};
          |                           ^
    cc1plus: all warnings being treated as errors

    Give every member a value, or use {} to set them all to zero. The next lesson, Constructors, destructors and the rule of zero, shows how to give a member a default value in the struct itself, so it can be left out on purpose.

    Common pitfallNo braces, no values

    Read read; without braces leaves quality uninitialized: reading it before you set it is undefined behavior, as with any uninitialized int (Variables). Members like std::string still start empty. Write Read read{}; to start every member at zero.

    Try it yourself

    Try it yourself

    A probability must be between 0 and 1, but nothing stops this program from storing 1.7. Turn Probability into a class with a private value, a set function that clamps values below 0 to 0 and above 1 to 1, and a const get function. Then set 0.25 and print it, and set 1.7 and print it.

    #include <print>
    
    struct Probability {
        double value;
    };
    
    int main() {
        Probability p{0.25};
        std::println("{}", p.value);
        p.value = 1.7; // not a probability
        std::println("{}", p.value);
    }

    Expected output

    0.25
    1
    Show a hint

    Make Probability a class, rename the member to a private value_, and add two public member functions: set, which clamps its argument to the range 0 to 1 before storing it, and get, which is const and returns value_. Create it with Probability p{}; so value_ starts at 0.

    Show a solution
    #include <print>
    
    class Probability {
    public:
        void set(double value) {
            if (value < 0.0) {
                value = 0.0;
            } else if (value > 1.0) {
                value = 1.0;
            }
            value_ = value;
        }
        double get() const { return value_; }
    
    private:
        double value_;
    };
    
    int main() {
        Probability p{};
        p.set(0.25);
        std::println("{}", p.get());
        p.set(1.7);
        std::println("{}", p.get());
    }

    With value_ private, set is the only way to change it, so it can never leave the range 0 to 1: that's the invariant. get is const because it only reads. Probability p{} sets value_ to 0 before the first set call.