Data Structures in C/C++

struct in C and class in C++

Group related data into one type, then see how a C++ class protects that data with private members and methods.

  • Intermediate
  • 5 min read
  • 2 runnable examples
What you'll learn
  • Defining a struct and accessing its fields
  • Functions that take a struct pointer in C
  • Classes, private state and member functions in C++
An account in each language
C struct
struct Account { ... };
  • fields are public
  • deposit(&acc, 25)
  • rules live in every caller
C++ class
class Account { ... };
  • balance is private
  • acc.deposit(25)
  • rules live in the class

Data and the code that changes it

The problem

A bank account has an owner and a balance. Keeping them in two separate variables gets messy as soon as there are many accounts, and nothing stops code from setting a balance to nonsense. You need one type that groups the data and, ideally, protects it.

Think of it like this

A struct is like a form with labeled boxes: owner, balance. Anyone holding the form can write in any box. A C++ class is like a bank counter: the data sits behind the glass, and you can only change it through the teller (member functions), who refuses invalid requests.

From a form and a bank counter to code
typedef struct { ... } Account;📋 A form with labeled boxes
account->balance += amount;✍️ C: write in the box through a pointer
class Account { std::string owner_; ... }🏦 C++: data kept behind the glass
account.deposit(25.0);🧑‍💼 Ask the teller, who checks the amount
A struct groups data; a class also controls how it changes.
In one sentence

A struct groups related fields under one type; a C++ class can also keep its fields private and allow changes only through its member functions.

Important points

  1. Account bundles owner and balance into one value.
  2. In C, deposit(&account, 25.0) receives a pointer and updates account->balance.
  3. In C++, balance_ is private, so code outside the class must call deposit.
  4. Both versions refuse non-positive amounts with if (amount > 0).

When to use it

  • Grouping related data: points, accounts, records, settings.
  • C++ classes whose data must stay valid, such as a balance that cannot go negative.
  • Passing many related values to a function as one argument.

When not to use it

  • Plain data with no rules to protect: a simple struct is clearer than a class with getters and setters.
  • Two values used together only once: separate variables may be enough.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

typedef struct {
    const char *owner;
    double balance;
} Account;

void deposit(Account *account, double amount) {
    if (amount > 0) {
        account->balance += amount;
    }
}

int main(void) {
    Account account = {"Ada", 100.0};
    deposit(&account, 25.0);
    printf("%s: %.2f\n", account.owner, account.balance);
    return 0;
}
Get a Run button for this example Result of running the code
Ada: 125.00
C++
Run code →
main.cpp
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>

class Account {
    std::string owner_;
    double balance_;

public:
    Account(std::string owner, double balance)
        : owner_(std::move(owner)), balance_(balance) {}

    void deposit(double amount) {
        if (amount > 0) {
            balance_ += amount;
        }
    }

    void print() const {
        std::cout << owner_ << ": " << std::fixed
                  << std::setprecision(2) << balance_ << '\n';
    }
};

int main() {
    Account account("Ada", 100.0);
    account.deposit(25.0);
    account.print();
}
Get a Run button for this example Result of running the code
Ada: 125.00

C and C++ comparison

The C design passes a pointer to the struct, and the deposit function changes the balance through it. The C++ class keeps balance_ private and offers deposit and print, so code outside the class cannot set an invalid balance directly.

C

Structures and operations are usually separate and allocation is explicit.

C++

Classes and containers can preserve invariants and manage resources automatically.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Add empty and capacity-boundary tests.
  • Implement cleanup and verify no leaks remain.
  • Compare operation complexity with a standard container.

struct in C and class in C++ at a glance

struct Point { int x; int y; };C: define a struct (note the semicolon)
struct Point p = {1, 2};C: create and initialize a struct
struct Point p = {.x = 1, .y = 2};C: designated initializers
typedef struct { int x, y; } Point;C: use Point without writing struct each time
p.x, ptr->xAccess a member directly, or through a pointer
Point p{1, 2};C++: create a struct with brace initialization
class Account { public: ... private: ... };C++: a class with public methods and private data
Point(int x, int y) : x(x), y(y) {}C++: a constructor with an initializer list
struct vs classC++: struct members are public by default, class members are private by default

Common mistakes with struct and class

Forgetting the semicolon after the definition

A struct or class definition ends with }; and leaving out the semicolon causes confusing errors on the next line.

Problem
struct Point {
    int x;
    int y;
}
Fix
struct Point {
    int x;
    int y;
};

Leaving out struct in C

In C, the type name is struct Point, not Point, unless you add a typedef.

Problem
struct Point { int x; int y; };
Point p = {1, 2};  /* error in C */
Fix
struct Point { int x; int y; };
struct Point p = {1, 2};

Using . with a pointer

Through a pointer, use -> (or (*ptr).x).

Problem
struct Point *ptr = &p;
ptr.x = 5;  /* error */
Fix
struct Point *ptr = &p;
ptr->x = 5;

Comparing structs with == in C

C has no == for structs. Compare the members you care about.

Problem
if (a == b) { /* error in C */ }
Fix
if (a.x == b.x && a.y == b.y) { /* equal */ }

Frequently asked questions

What is the difference between a struct and a class in C++?

Only the default access: struct members and base classes are public by default, class members are private by default. Both can have constructors, methods and inheritance. By convention, struct is used for simple data and class for types with behavior.

Can a struct have functions in C?

No, C structs hold only data. You can store function pointers in a struct, or write functions that take a pointer to the struct, which is how C code imitates methods.

What does typedef struct do?

It gives the struct a type name, so you can write Point p; instead of struct Point p; in C. C++ does not need it.

Why is sizeof(struct) bigger than the sum of its members?

The compiler may add padding between members so each one sits at an address the processor can read efficiently. Ordering members from largest to smallest often reduces the padding.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges