Cpp object memory allocation
Programming / cpp / learn cpp
Encapsulation
- Use of private/protected fields
- Getters and setters (if needed)
- Const-correctness (const member functions)
- Immutable objects
Inheritance
- Base and derived classes
- public, private, and protected inheritance
- Virtual functions
- Constructor chaining (Base(args))
Polymorphism
- Function overriding
- Virtual destructors
- Pure virtual functions (= 0)
- Abstract base classes
- Runtime polymorphism via pointers or references
- The role of virtual and override
Constructors and Object Lifecycle
- Default constructor, copy constructor, move constructor
- Copy assignment, move assignment
- The Rule of Three / Rule of Five
- Destructor
- RAII (Resource Acquisition Is Initialization)
Operator Overloading
- Overload operators like +, ==, <<, [], etc.
- Understand which should be friend, member, or non-member
- Best practices and dangers
Smart Pointers and Ownership (Modern C++)
- std::unique_ptr, std::shared_ptr, std::weak_ptr
- Ownership models
- Avoiding raw new and delete
- Avoiding memory leaks and dangling pointers
Templates and Generic OOP (Advanced)
- Template classes and functions
- Combining OOP and templates
- CRTP (Curiously Recurring Template Pattern)
- Type traits (std::is_base_of, etc.)
Composition over Inheritance
- Prefer combining objects over subclassing
- Delegation
- Aggregation vs composition
Design Patterns (Optional, Practical)
- Singleton (with std::unique_ptr)
- Factory
- Strategy
- Observer
- Builder
Modern C++ OOP Best Practices
- Favor composition and RAII
- Prefer = default / = delete over writing boilerplate
- Avoid unnecessary inheritance
- Use final to prevent further inheritance when needed
- Use explicit on single-arg constructors
- Don’t overuse setters/getters — prefer invariants
Allocation
- Stack
- raw
- smart pointers
Using valgrind
Find leak
For example comment the delete dog line (25) and run valgrind it found that dog object in line 21 not freed
flowchart TD
A[Camera] -->|ROS2 topic: camera/error_xy| B[Your ROS2 Node\nmpc_attitude_controller.py]
subgraph RUNTIME
B -->|build OCP in Python| C[acados_template\n]
C -->|codegen on first run|\nD[/c_generated_code/]
D -->|compiled solver .so|\nE[[libacados_ocp_solver_img_ang_mpc.so]]
E -->|calls into| F[[acados C library]]
F --> G[HPIPM & BLASFEO\n]
E -->|solve MPC @ 20 Hz| B
B -->|publish AttitudeTarget| H[MAVROS\n/setpoint_raw/attitude]
H --> I[ArduPilot\n]
end