Struct vs Class
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 37 of 104.
In C++, struct and class are nearly identical. Both can have member variables, member functions, constructors, and support inheritance. The only difference is their default access level.
In a class, members are private by default. In a struct, members are public by default:
struct Point {
int x; // public by default
int y; // public by default
};
class Circle {
double radius; // private by default
public:
double getRadius() { return radius; }
};This also applies to inheritance. A struct inherits publicly by default, while a class inherits privately:
struct DerivedStruct : Base {}; // public inheritance
class DerivedClass : Base {}; // private inheritanceBeyond these defaults, there's no technical difference. However, convention matters.
Most C++ programmers use struct for simple data containers with public members (like a coordinate or configuration), and class when encapsulation and behavior are important. Following this convention makes your code's intent clearer to other developers.
Challenge
EasyLet's build a simple configuration system that demonstrates when to use struct versus class based on C++ conventions. You'll create a struct for simple data that's meant to be openly accessible, and a class for data that needs encapsulation and controlled access.
You'll create two files to organize your code:
Config.h: Define both a struct and a class that represent different kinds of configuration data.First, create a
structcalledDimensions— a simple data container for width and height (bothint). Since structs have public members by default, these should be directly accessible without getters. Include a methodarea()that returns the product of width and height.Then, create a
classcalledAppConfigthat manages application settings with proper encapsulation. It should store an app name (string) and aDimensionsobject for the window size. Since class members are private by default, you'll need to explicitly make your public interface accessible. Provide:- A constructor that takes the app name, width, and height
- A getter
getAppName()that returns the name - A getter
getWindowSize()that returns theDimensions - A method
displayConfig()that prints:"App: <name>, Window: <width>x<height>, Area: <area>"
main.cpp: Demonstrate the difference between struct and class usage. Read an app name, width, and height from input (three separate lines), then:- Create a
Dimensionsstruct directly with the width and height values — access its members directly to print:"Direct struct access: <width> x <height>" - Create an
AppConfigobject with all three values - Call
displayConfig()to show the full configuration - Use the getter to retrieve the window dimensions and print:
"Via getter - Area: <area>"
- Create a
This challenge highlights the convention: use struct when you have simple, transparent data (like coordinates or dimensions), and use class when you want to control access and add behavior around your data.
Convert width and height inputs from strings to integers using std::stoi(). Don't forget header guards in your header file.
Cheat sheet
In C++, struct and class are nearly identical, with one key difference: their default access level.
In a struct, members are public by default:
struct Point {
int x; // public by default
int y; // public by default
};In a class, members are private by default:
class Circle {
double radius; // private by default
public:
double getRadius() { return radius; }
};This also applies to inheritance:
struct DerivedStruct : Base {}; // public inheritance by default
class DerivedClass : Base {}; // private inheritance by defaultConvention: Use struct for simple data containers with public members, and class when encapsulation and behavior are important.
Try it yourself
#include <iostream>
#include <string>
#include "Config.h"
using namespace std;
int main() {
// Read input
string appName;
string widthStr;
string heightStr;
getline(cin, appName);
getline(cin, widthStr);
getline(cin, heightStr);
int width = stoi(widthStr);
int height = stoi(heightStr);
// TODO: Create a Dimensions struct with width and height
// Access its members directly to print: "Direct struct access: <width> x <height>"
// TODO: Create an AppConfig object with appName, width, and height
// TODO: Call displayConfig() on the AppConfig object
// TODO: Use getWindowSize() getter to get dimensions and print: "Via getter - Area: <area>"
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container