So far, every variable we've created holds one kind of value: an int, a double, a std::string, or an array of identical elements. But real-world things have several properties of different types. A student has a name (text), a roll number (integer) and a CGPA (decimal number).
C++ gives us three ways to build our own types from simpler ones:
Structures (
struct): group several related values together.Unions (
union): store one of several possible values in the same memory.Enumerations (
enumandenum class): give names to a fixed set of choices.
If you know C, all three will look familiar, but C++ adds important improvements, especially enum class. Structures are also the bridge to the next topic, Classes & Objects.
Structures
A structure is a user-defined type that groups together variables (called members or data members) of possibly different types under one name.
struct Student
{
std::string name;
int roll;
double cgpa;
}; // don't forget this semicolon!
This definition creates a new type called Student. It does not create any variable yet; it's a blueprint. We then create variables of that type and access members with the dot operator (.):
Student s; // in C++ we don't need to write "struct Student s;"
s.name = "Asha";
s.roll = 101;
Each Student variable gets its own copy of all three members, laid out together in memory.
A Complete Example
#include <iostream>
#include <string>
struct Student
{
std::string name;
int roll = 0; // default member initializer (C++11)
double cgpa = 0.0;
void print() const // a member function inside a struct
{
std::cout << roll << " " << name << " " << cgpa << '\n';
}
};
int main()
{
Student s1; // name "", roll 0, cgpa 0.0
s1.name = "Asha";
s1.roll = 101;
s1.cgpa = 8.9;
Student s2{"Ravi", 102, 7.5}; // aggregate initialization
Student s3{.name = "Meena", .roll = 103}; // designated initializers (C++20), cgpa stays 0.0
Student* ptr = &s2;
ptr->cgpa = 7.8; // -> works on a pointer to a struct
s1.print();
s2.print();
s3.print();
return 0;
}
Output:
101 Asha 8.9
102 Ravi 7.8
103 Meena 0
Let's go through the new ideas one by one.
1. Default member initializers (C++11). Writing int roll = 0; inside the struct means "if nobody gives roll a value, start it at 0". Without it, Student s1; would leave roll and cgpa uninitialized (garbage), just like a plain local int. name is a std::string, which always starts as an empty string.
2. Aggregate initialization. Student s2{"Ravi", 102, 7.5}; assigns the values to the members in the order they are declared. Members we leave out get their default member initializer, or are value-initialized (0) if they don't have one.
3. Designated initializers (C++20). {.name = "Meena", .roll = 103} names the members explicitly, which is clearer when a struct has many members. C++ is stricter than C here: the designators must appear in declaration order, and you cannot mix designated and positional values in one initializer.
4. Member functions. Unlike C, a C++ struct can contain functions. print() can use roll, name and cgpa directly because it runs on a particular Student. The const after print() promises it won't modify the struct. We'll study member functions properly in Classes & Objects.
5. The arrow operator. With a pointer to a struct, ptr->cgpa is a shorter way of writing (*ptr).cgpa. The parentheses are needed because . has higher precedence than *.
Nested Structs, Arrays of Structs and Functions
Structs can contain other structs, can be stored in arrays, and can be passed to and returned from functions just like built-in types.
#include <iostream>
#include <string>
struct Point
{
int x;
int y;
};
struct Rectangle
{
Point topLeft; // a struct inside a struct
Point bottomRight;
};
int area(const Rectangle& r) // pass by const reference: no copy
{
return (r.bottomRight.x - r.topLeft.x) * (r.bottomRight.y - r.topLeft.y);
}
Point midpoint(const Rectangle& r) // return a struct by value
{
return {(r.topLeft.x + r.bottomRight.x) / 2, (r.topLeft.y + r.bottomRight.y) / 2};
}
int main()
{
Rectangle rooms[] = {
{{0, 0}, {4, 3}},
{{2, 1}, {8, 5}},
};
for (const Rectangle& r : rooms)
{
auto [mx, my] = midpoint(r); // structured binding (C++17)
std::cout << "area = " << area(r)
<< ", centre = (" << mx << ", " << my << ")\n";
}
Point a{1, 2};
Point b = a; // copies every member
b.x = 99;
std::cout << "a = (" << a.x << ", " << a.y << "), b = (" << b.x << ", " << b.y << ")\n";
return 0;
}
Output:
area = 12, centre = (2, 1)
area = 24, centre = (5, 3)
a = (1, 2), b = (99, 2)
Points to notice:
Pass large structs by
constreference (const Rectangle&), as we learned in the References topic. Passing by value copies every member; for a struct holding strings or arrays that can be expensive.Returning a struct by value is fine. Modern compilers construct the result directly in the caller (copy elision), so there is no extra copy.
Structured bindings (C++17):
auto [mx, my] = midpoint(r);unpacks the members of the returnedPointinto two names, in declaration order.Assignment copies member by member. After
Point b = a;,aandbare completely independent, so changingb.xdoesn't toucha. (Arrays can't be assigned like this, but a struct containing an array can: the whole array is copied.)Structs can not be compared with
==automatically. You must compare members yourself, or ask the compiler to generate the comparison (bool operator==(const Point&) const = default;, C++20), which we'll understand in the Operator Overloading topic.
Memory Layout and Padding
You might expect sizeof a struct to be the sum of its members' sizes. Often it is larger. Most processors read data fastest when each value sits at an address that is a multiple of its alignment (for a 4-byte int, typically a multiple of 4). So the compiler inserts unused padding bytes between members.
#include <iostream>
struct Bad
{
char a; // 1 byte
int b; // 4 bytes
char c; // 1 byte
};
struct Good
{
int b; // 4 bytes
char a; // 1 byte
char c; // 1 byte
};
int main()
{
std::cout << "sizeof(Bad) = " << sizeof(Bad) << '\n';
std::cout << "sizeof(Good) = " << sizeof(Good) << '\n';
std::cout << "alignof(int) = " << alignof(int) << '\n';
std::cout << "alignof(Bad) = " << alignof(Bad) << '\n';
return 0;
}
Output (g++ on x86-64; sizes and alignment are implementation-defined):
sizeof(Bad) = 12
sizeof(Good) = 8
alignof(int) = 4
alignof(Bad) = 4
Here is how the bytes are arranged (each cell is one byte, p is padding):
Bad (12 bytes)
offset: 0 1 2 3 4 5 6 7 8 9 10 11
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ a │ p │ p │ p │ b │ b │ b │ b │ c │ p │ p │ p │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
Good (8 bytes)
offset: 0 1 2 3 4 5 6 7
┌───┬───┬───┬───┬───┬───┬───┬───┐
│ b │ b │ b │ b │ a │ c │ p │ p │
└───┴───┴───┴───┴───┴───┴───┴───┘
In
Bad,bmust start at a multiple of 4, so 3 padding bytes followa.Padding is also added at the end, so that the struct's size is a multiple of its own alignment. That way, every element in an array of
Badstays correctly aligned.Members are stored in the order they are declared (guaranteed for all members since C++23; earlier standards guaranteed it only among members with the same access level), so ordering members from largest to smallest alignment usually minimises padding.
This is a common GATE and interview question: "What is sizeof this struct?" Remember to assume the typical alignment (char 1, short 2, int 4, double 8 on 64-bit systems) unless the question says otherwise.
Note: An empty struct (
struct E {};) hassizeof(E) == 1in C++, never 0. Every object must have a distinct address, so even an empty object occupies at least one byte.
struct in C vs struct in C++
| Feature | C | C++ |
|---|---|---|
| Declaring a variable | struct Student s; (or use typedef) | Student s; |
| Member functions | Not allowed | Allowed |
| Default member initializers | Not allowed | Allowed (C++11) |
Access specifiers (private, etc.) | No | Yes (default is public) |
| Constructors, inheritance | No | Yes |
| Empty struct | Not allowed by the C standard | Allowed, sizeof is at least 1 |
| Designated initializers | Any order, nesting allowed | Declaration order only (C++20) |
In fact, in C++ a struct is almost exactly the same as a class. The only difference is the default access level, which we'll see in the next topic.
Unions
A union is a user-defined type whose members all share the same memory location. At any moment, it holds a value for at most one of its members, called the active member.
The syntax looks like a struct, but the behaviour is very different:
struct S { int i; double d; char c; }; union U { int i; double d; char c; };
S: ┌──────┬──────┬──────────┬──────┬──────┐ U: ┌──────────────────────┐
│ i │ pad │ d │ c │ pad │ │ i / d / c (overlap) │
└──────┴──────┴──────────┴──────┴──────┘ └──────────────────────┘
every member has its own space all members start at offset 0
The size of a union is at least the size of its largest member (plus any padding needed for alignment).
#include <iostream>
union Value
{
int i;
double d;
char c;
};
int main()
{
std::cout << "sizeof(int) = " << sizeof(int) << '\n';
std::cout << "sizeof(double) = " << sizeof(double) << '\n';
std::cout << "sizeof(Value) = " << sizeof(Value) << '\n';
Value v;
v.i = 65; // i is now the active member
std::cout << "v.i = " << v.i << '\n';
v.d = 2.5; // d becomes active; i is no longer valid
std::cout << "v.d = " << v.d << '\n';
std::cout << "&v.i == &v.d ? " << (static_cast<void*>(&v.i) == static_cast<void*>(&v.d) ? "yes" : "no") << '\n';
return 0;
}
Output:
sizeof(int) = 4
sizeof(double) = 8
sizeof(Value) = 8
v.i = 65
v.d = 2.5
&v.i == &v.d ? yes
All members have the same address. Writing to v.d overwrites the bytes that v.i used, so v.i is no longer meaningful.
The Big Rule: Read Only the Active Member
In C++, reading a member that is not the active one is undefined behavior (with a narrow exception for structs that share a "common initial sequence"). For example, after v.d = 2.5;, reading v.i is undefined behavior in C++.
This is a real difference from C, where reading another member ("type punning") is allowed and reinterprets the bytes. Many C++ compilers, including GCC, do support it in practice, but portable C++ code should use std::bit_cast (C++20) or std::memcpy to reinterpret bytes.
Tagged Unions
Because the union itself doesn't remember which member is active, we usually pair it with a tag that records it. This pattern is called a tagged union (or discriminated union).
#include <iostream>
// A tagged union: the tag remembers which member is active
struct Shape
{
enum Kind { Circle, Square } kind;
union
{
double radius; // valid when kind == Circle
double side; // valid when kind == Square
}; // anonymous union: members used directly
};
double area(const Shape& s)
{
if (s.kind == Shape::Circle)
return 3.14159 * s.radius * s.radius;
else
return s.side * s.side;
}
int main()
{
Shape a;
a.kind = Shape::Circle;
a.radius = 2.0;
Shape b;
b.kind = Shape::Square;
b.side = 3.0;
std::cout << "circle area = " << area(a) << '\n';
std::cout << "square area = " << area(b) << '\n';
return 0;
}
Output:
circle area = 12.5664
square area = 9
The union inside Shape has no name. This is an anonymous union: its members (radius, side) are accessed as if they were members of Shape itself. The kind member uses an enum, which we'll explain in the next section.
Unions save memory, which matters in embedded systems, network packet parsing and interpreters. But a hand-written tagged union is easy to get wrong: nothing stops you from setting kind = Circle and then reading side.
The Safe Modern Alternative: std::variant
C++17 added std::variant (header <variant>), a type-safe union that keeps track of the active type for you and refuses wrong access.
#include <iostream>
#include <string>
#include <variant> // C++17
int main()
{
std::variant<int, double, std::string> v = 42; // holds an int
std::cout << "index " << v.index() << ": " << std::get<int>(v) << '\n';
v = std::string("hello"); // now holds a string
std::cout << "index " << v.index() << ": " << std::get<std::string>(v) << '\n';
if (std::holds_alternative<int>(v))
std::cout << "still an int\n";
else
std::cout << "not an int any more\n";
try
{
std::cout << std::get<int>(v) << '\n'; // wrong type
}
catch (const std::bad_variant_access&)
{
std::cout << "bad_variant_access: v does not hold an int\n";
}
return 0;
}
Output:
index 0: 42
index 2: hello
not an int any more
bad_variant_access: v does not hold an int
index() tells us which alternative is active (0 for int, 1 for double, 2 for std::string), and a wrong std::get throws an exception instead of silently returning garbage. (try/catch is covered in Exception Handling.) A plain union also cannot safely hold a std::string without extra manual work, while std::variant handles it automatically.
| Point | struct | union | std::variant (C++17) |
|---|---|---|---|
| Members stored | All, each in its own space | One at a time, shared space | One at a time, shared space |
| Size | At least sum of members (+ padding) | At least largest member | Largest alternative + a small index |
| Knows the active member? | Not applicable | No | Yes |
| Wrong access | Not applicable | Undefined behavior | Throws std::bad_variant_access |
Can hold std::string easily? | Yes | No (needs manual construction/destruction) | Yes |
Enumerations
Often a variable should only take a few specific values: the days of the week, the state of an order, the colour of a traffic light. We could use int codes (0 = red, 1 = yellow ...), but then light = 17; compiles happily and the code is full of "magic numbers".
An enumeration is a user-defined type whose values are restricted to a set of named constants called enumerators.
C++ has two kinds: the old unscoped enum (inherited from C) and the newer scoped enum, written enum class (C++11).
Unscoped Enums
#include <iostream>
enum Color { Red, Green, Blue }; // unscoped (plain) enum
enum Level { Low = 1, Medium = 5, High }; // High is 6
int main()
{
Color c = Green;
int n = c; // implicit conversion to int is allowed
std::cout << "Green = " << n << '\n';
std::cout << "High = " << High << '\n';
if (c == 1) // compiles: compares with an int
std::cout << "c == 1 is true\n";
// Color bad = 2; // error: no implicit int -> enum conversion
Color fromInt = static_cast<Color>(2);
std::cout << "fromInt = " << fromInt << '\n';
return 0;
}
Output:
Green = 1
High = 6
c == 1 is true
fromInt = 2
The rules for values:
The first enumerator is
0unless given a value.Each following enumerator is one more than the previous one. That's why
Highis 6 (afterMedium = 5).Two enumerators may have the same value.
Unscoped enums have two weaknesses:
Names leak into the surrounding scope.
Red,Green,Bluebecome global names. If another enum also has aRed, the program fails to compile with a redefinition error.They silently convert to
int.c == 1compiles, and so doesGreen + Medium, which makes no sense. (Since C++20, arithmetic between two different enumeration types is deprecated and g++ warns about it with-Wdeprecated-enum-enum-conversion; C++26 turns it into an error. Mixing an enum with a plainint, as inc == 1, is still allowed.) The type system isn't protecting us much.
Scoped Enums: enum class (C++11)
A scoped enumeration fixes both problems. Its enumerators must be written with the enum's name (TrafficLight::Red), and there is no implicit conversion to or from integers.
#include <iostream>
#include <cstdint>
#include <utility> // std::to_underlying (C++23)
enum class TrafficLight { Red, Yellow, Green }; // scoped enum (C++11)
enum class Signal { Red, Blue }; // no clash with TrafficLight::Red
enum class Status : std::uint8_t // fixed underlying type
{
Ok = 0,
NotFound = 44,
Error = 50
};
const char* action(TrafficLight t)
{
switch (t)
{
using enum TrafficLight; // C++20: no need to repeat TrafficLight::
case Red: return "Stop";
case Yellow: return "Get ready";
case Green: return "Go";
}
return "?";
}
int main()
{
TrafficLight t = TrafficLight::Yellow;
std::cout << action(t) << '\n';
// int x = t; // error: no implicit conversion
int x = static_cast<int>(t); // explicit conversion is fine
std::cout << "Yellow as int = " << x << '\n';
Status s = Status::NotFound;
std::cout << "sizeof(Status) = " << sizeof(Status) << '\n';
std::cout << "NotFound = " << +std::to_underlying(s) << '\n'; // + prints the number, not a char
Signal sig = Signal::Red;
std::cout << (sig == Signal::Red ? "signal red\n" : "other\n");
return 0;
}
Output:
Get ready
Yellow as int = 1
sizeof(Status) = 1
NotFound = 44
signal red
New features used here:
Both enums have a
Red, and there's no conflict, because the names live insideTrafficLight::andSignal::.Underlying type.
enum class Status : std::uint8_tstores each value in one byte. Without: type, anenum classusesint. (A plain enum without: typeuses an implementation-chosen integer type large enough for its values.)std::to_underlying(C++23) converts an enum to its underlying integer type. It's the same asstatic_cast<std::uint8_t>(s)but you don't have to repeat the type. The unary+promotes theuint8_ttoint; without it,std::coutwould print it as a character.using enum(C++20) brings the enumerators into the current scope, so inside theswitchwe can writecase Red:instead ofcase TrafficLight::Red:.A scoped enum can't be printed directly with
std::cout << t(no implicit conversion), so we convert it explicitly or write a function such asaction().
Tip: when you
switchover an enum without adefaultlabel, GCC's-Wallwarns if you forget an enumerator (-Wswitch). This is a great reason to prefer enums over integer codes.
| Point | enum (unscoped) | enum class (scoped, C++11) |
|---|---|---|
| Accessing enumerators | Red | Color::Red |
| Names leak into enclosing scope? | Yes | No |
Implicit conversion to int | Yes | No (use static_cast or std::to_underlying) |
| Default underlying type | Implementation-defined integer type | int |
| Can specify underlying type | Yes (C++11) | Yes |
| Recommended for new code? | Rarely | Yes |
Common Mistakes
Forgetting the semicolon after the closing brace of a
struct,unionorenum. The error message often points to the next line, which is confusing.Assuming
sizeofa struct is the sum of its members. Padding usually makes it larger.Leaving members uninitialized.
Student s;without default member initializers leavesintanddoublemembers with garbage values. Use= 0in the struct orStudent s{};.Passing big structs by value when a
const&would avoid a copy.Reading a union member that isn't active. It's undefined behavior in C++. Use a tag, or
std::variant.Using plain enums in new code and getting name clashes or nonsense comparisons like
color == 3.Expecting
std::cout <<to print an enum's name. It prints the number (for plain enums) or doesn't compile (forenum class). Up to C++23 there is no built-in enum-to-string conversion; you write a function (or aswitch) yourself. C++26 adds static reflection, which finally makes a generic one possible.
Interview / GATE Questions
1. On a typical 64-bit system, what is sizeof(struct T { char a; double b; char c; })?
24. a at offset 0, 7 bytes of padding, b at offset 8 (8 bytes), c at offset 16, then 7 bytes of tail padding so the size is a multiple of 8 (the alignment of double). Reordering to double b; char a; char c; gives 16.
2. What is the size of union U { int a[5]; double d; char c; } on a typical 64-bit system?
24. The largest member is int a[5] = 20 bytes, but the union's alignment is 8 (because of double), so it is rounded up to 24.
3. What is the difference between a structure and a union?
In a structure every member has its own storage, so all members can hold values at the same time, and the size is at least the sum of the members. In a union all members share the same storage, only one member (the active one) holds a value at a time, and the size is at least the size of the largest member.
4. Why is enum class preferred over a plain enum?
Its enumerators are scoped (no name clashes with other enums or variables), it doesn't implicitly convert to int (so meaningless comparisons and arithmetic are compile errors), and its underlying type defaults to int (so it can be forward-declared without specifying one).
5. What are the values of the enumerators in enum E { A, B = 10, C, D = 3, F };?
A = 0, B = 10, C = 11, D = 3, F = 4. Each enumerator without a value is one more than the previous one.
6. What is the only difference between struct and class in C++?
The default access level: members (and base classes) of a struct are public by default, while those of a class are private by default. Everything else (member functions, constructors, inheritance) works the same. We'll see this in Classes & Objects.
Summary
A
structgroups related members of different types. Use.on objects and->on pointers.Initialize structs with default member initializers (C++11), aggregate initialization
{...}, or designated initializers{.x = 1}(C++20, in declaration order).Padding aligns members, so
sizeofa struct can exceed the sum of its members. Ordering members from largest to smallest reduces it.A
unionstores one member at a time in shared memory. Its size is at least that of its largest member. Reading an inactive member is undefined behavior in C++.Prefer
std::variant(C++17) for a type-safe union.An enum names a set of constants. Prefer
enum class(C++11): scoped names and no implicit conversion toint.std::to_underlying(C++23) converts an enum to its integer value;using enum(C++20) brings enumerators into scope.