Classes, objects and lifetime
Use a CAN message to distinguish a type definition from an actual object.
A class describes a type
A class groups data and operations. Each object has its own non-static data members. A non-static member function works with a particular object through its implicit this pointer. Access control helps keep the object's rules consistent.
Construction establishes valid state
Initialize members in a constructor's member initializer list. Actual member initialization order follows declaration order, not the order written in that list. Design constructors so a successfully created object is usable.
Lifetime boundaries
An automatic object's destructor runs when its scope is left normally, including stack unwinding where exceptions are supported. Object lifetime is different from how long raw storage remains allocated. A pointer to a destroyed object cannot safely be used to access that object.
struct CanMessage {
unsigned id;
unsigned char length;
CanMessage(unsigned value) : id(value), length(0) {}
};
CanMessage request{0x123};Follow each transition
Type defined
A class declaration does not create an instance.
Conceptual sequence. Timing is slowed for learning; it is not a hardware measurement.
Your investigation
A constructor initializes length from another member declared after it. Why can reordering the initializer list fail to fix the bug?
Reveal the investigation checklist
- Read member declaration order.
- Remove dependencies on uninitialized members.
- Enable compiler reorder warnings.
- Test the constructed object's invariant.
What determines member initialization order?
Answer the knowledge check correctly to complete this lesson.
Think through Classes, objects and lifetime
Ask for an explanation, an automotive example or a question that tests your understanding.
Checking mentor availability…