1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M4 Structs
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
25Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M4 Structs

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
25Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Structs

Overview

Primitive arrays are powerful, but they have a fatal flaw: they can only hold one single data type. If you want to store a Player in a game, you need an int for their Health, a string for their Name, and a bool for their Status. Storing these in three separate variables is messy and unscalable.

A Struct (Structure) solves this by allowing developers to create custom, User-Defined Data Types. It essentially clumps different primitive variables together into a single, cohesive unit. You can pass a single Player struct to a function instead of passing 3 separate variables.

Syntax

cpp
#include <iostream>
#include <string>

// 1. Defining the blueprint for the custom Data Type
struct Player {
    std::string name;
    int health;
    int damage;
};

int main() {
    // 2. Creating an 'Instance' (a physical object in memory)
    Player p1;
    
    // 3. Accessing members using the Dot Operator (.)
    p1.name = "Knight";
    p1.health = 100;
    
    // 4. Uniform Initialization (Modern C++ shortcut)
    Player p2 = {"Mage", 50, 200};
    
    return 0;
}

Common Pitfalls

  • Forgetting the semicolon (;) at the end of the Struct definition. Unlike functions, structurally defining a struct strictly requires a semicolon at the final closing brace: struct X { };. Forgetting this causes the compiler to completely freak out.
  • Padding and Memory alignment. A struct with a char (1 byte), then a double (8 bytes), then a char (1 byte) does NOT take 10 bytes. The CPU adds hidden 'Padding' bytes to align memory for faster access, often inflating the struct size to 24 bytes! Order your variables from largest to smallest to save RAM.

Interview Questions

In C++, what is the fundamental, technical difference between a struct and a class?

By absolute definition in C++, they are physically identical in how they operate in memory. The ONLY technical difference is Default Visibility. In a struct, all members are completely public by default. In a class, all members are strictly private by default. Historically, structs are used for simple 'Plain Old Data' (POD) objects, while classes are used for complex OOP behavior.

Real-World Example

Using an Array of Structs to easily manage a database of multiple complex entities.

example
cpp
#include <iostream>
#include <string>

struct Enemy {
    std::string type;
    int hp;
};

int main() {
    // Creating an array of our custom data type!
    Enemy horde[3] = {
        {"Goblin", 30},
        {"Orc", 100},
        {"Troll", 250}
    };
    
    // Blazing fast access to structured data
    for (int i = 0; i < 3; i++) {
        std::cout << horde[i].type << " HP: " << horde[i].hp << "\n";
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of Structs with these quick questions.

Question 1

Why is a Struct heavily preferred over a standard Array for storing data about a real-world object (like a Book or a Car)?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Structs

Overview

Primitive arrays are powerful, but they have a fatal flaw: they can only hold one single data type. If you want to store a Player in a game, you need an int for their Health, a string for their Name, and a bool for their Status. Storing these in three separate variables is messy and unscalable.

A Struct (Structure) solves this by allowing developers to create custom, User-Defined Data Types. It essentially clumps different primitive variables together into a single, cohesive unit. You can pass a single Player struct to a function instead of passing 3 separate variables.

Syntax

cpp
#include <iostream>
#include <string>

// 1. Defining the blueprint for the custom Data Type
struct Player {
    std::string name;
    int health;
    int damage;
};

int main() {
    // 2. Creating an 'Instance' (a physical object in memory)
    Player p1;
    
    // 3. Accessing members using the Dot Operator (.)
    p1.name = "Knight";
    p1.health = 100;
    
    // 4. Uniform Initialization (Modern C++ shortcut)
    Player p2 = {"Mage", 50, 200};
    
    return 0;
}

Common Pitfalls

  • Forgetting the semicolon (;) at the end of the Struct definition. Unlike functions, structurally defining a struct strictly requires a semicolon at the final closing brace: struct X { };. Forgetting this causes the compiler to completely freak out.
  • Padding and Memory alignment. A struct with a char (1 byte), then a double (8 bytes), then a char (1 byte) does NOT take 10 bytes. The CPU adds hidden 'Padding' bytes to align memory for faster access, often inflating the struct size to 24 bytes! Order your variables from largest to smallest to save RAM.

Interview Questions

In C++, what is the fundamental, technical difference between a struct and a class?

By absolute definition in C++, they are physically identical in how they operate in memory. The ONLY technical difference is Default Visibility. In a struct, all members are completely public by default. In a class, all members are strictly private by default. Historically, structs are used for simple 'Plain Old Data' (POD) objects, while classes are used for complex OOP behavior.

Real-World Example

Using an Array of Structs to easily manage a database of multiple complex entities.

example
cpp
#include <iostream>
#include <string>

struct Enemy {
    std::string type;
    int hp;
};

int main() {
    // Creating an array of our custom data type!
    Enemy horde[3] = {
        {"Goblin", 30},
        {"Orc", 100},
        {"Troll", 250}
    };
    
    // Blazing fast access to structured data
    for (int i = 0; i < 3; i++) {
        std::cout << horde[i].type << " HP: " << horde[i].hp << "\n";
    }
    
    return 0;
}

Check Your Knowledge

Test your understanding of Structs with these quick questions.

Question 1

Why is a Struct heavily preferred over a standard Array for storing data about a real-world object (like a Book or a Car)?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A