C++ STRUCT VS CLASS:
┌─────────────────┬──────────────────────────┬────────────────────────────┐
│ Feature │ struct │ class │
├─────────────────┼──────────────────────────┼────────────────────────────┤
│ Default Members │ PUBLIC │ PRIVATE │
│ Default Inherit │ PUBLIC │ PRIVATE │
│ Idiomatic Use │ Passive Data Structures │ Encapsulated Objects / OOP │
└─────────────────┴──────────────────────────┴────────────────────────────┘Structures in C++: Building Custom Data Records With struct
Direct Answer & Core Concept
Detailed Explanation & Mechanics
1. Struct vs Class Default Access:
2. Struct Memory Alignment & Padding:
Compilers insert padding bytes between struct members to align them to CPU word boundaries for faster memory bus transfers (alignof(Type)).
Runnable Code Example: Structures in C++
C++20 / C++23#include <iostream>
#include <string>
// Plain Old Data (POD) / Aggregate struct
struct DatabaseRecord {
int recordId;
std::string tableName;
double queryLatencyMs;
void display() const {
std::cout << "[Record #" << recordId << "] Table: " << tableName
<< " | Latency: " << queryLatencyMs << " ms
";
}
};
int main() {
// Designated initializers (C++20)
DatabaseRecord record{1001, "users_auth", 1.42};
record.display();
std::cout << "DatabaseRecord Size: " << sizeof(record) << " bytes
";
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: What is struct memory padding and alignment in C++?
Q: What is an aggregate struct in C++?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
struct for passive Plain Old Data (POD) / Data Transfer Objects (DTOs).2. Use
class when enforcing invariants, private encapsulation, and complex behavior.3. Order struct data members from largest to smallest to minimize memory padding waste.