struct in C and class in C++
Model related state and behavior.
What is struct in C and class in C++?
C structs group data; C++ classes can enforce invariants by combining private state with member functions.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
C and C++ code examples
#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;
}
Ada: 125.00
#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();
}
Ada: 125.00
C and C++ comparison
The C design passes a struct pointer to functions. The C++ class keeps balance private and exposes operations, making invalid direct state changes harder.
Structures and operations are usually separate and allocation is explicit.
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.
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