Back to results for “OOP & Classes”
C++ › Constexpr & Compile-Time

Can constexpr be used with classes and containers?

Advanced

Answer

Yes. Constructors and member functions can be constexpr, allowing literal (constexpr-constructible) types to be created and manipulated at compile time. C++20 greatly expanded this: constexpr std::vector and std::string, constexpr dynamic allocation (that doesn't escape constant evaluation), and constexpr algorithms, enabling far richer compile-time programming.
struct Point {
    int x, y;
    constexpr Point(int a, int b) : x(a), y(b) {}
    constexpr int sum() const { return x + y; }
};
constexpr Point p(1,2); static_assert(p.sum()==3);
Real-world example A constexpr geometry type computes fixed layout coordinates entirely at compile time.

Common follow-ups: What is a literal type? | What did C++20 add for constexpr containers?