C++•Classes & OOP
C++ Classes and Object-Oriented Programming (OOP)
Learn encapsulation, constructor member initializer lists, and RAII resource management in C++ classes.
Syntax
class ClassName {
private:
int secret;
public:
ClassName(int s) : secret(s) {}
};
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| private | Access Specifier | Accessible only within class member methods. |
| public | Access Specifier | Accessible to external callers and instances. |
| Member Initializer List | Constructor Syntax | : member(value) sets state before constructor body. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <string>
class ServerNode {
private:
std::string hostname;
int port;
bool isOnline;
public:
// Constructor with Member Initializer List
ServerNode(std::string name, int p)
: hostname(std::move(name)), port(p), isOnline(false) {}
void start() {
isOnline = true;
std::cout << "[NODE] " << hostname << ":" << port << " started successfully.\n";
}
void displayStatus() const {
std::cout << "Host: " << hostname << " | Port: " << port
<< " | Status: " << (isOnline ? "ONLINE" : "OFFLINE") << "\n";
}
};
int main() {
ServerNode node("api-primary", 8080);
node.displayStatus();
node.start();
node.displayStatus();
return 0;
}Expected Output:
Host: api-primary | Port: 8080 | Status: OFFLINE [NODE] api-primary:8080 started successfully. Host: api-primary | Port: 8080 | Status: ONLINE
How It Works: Step-by-Step
- Lines 4-8: Private member variables encapsulated inside class.
- Lines 12-13: Uses modern member initializer list with std::move.
- Line 20: const member function guarantees no mutation of object state.
Key Concepts
- Prefer member initializer lists (: var(val)) over assigning inside constructor bodies.
- Mark member functions const if they do not modify object attributes.
- Encapsulation hides internal implementation details behind public API interfaces.
Common Mistake: Forgetting the trailing semicolon after class declaration
In C++, every class declaration must end with a semicolon after the closing brace };.
❌ Incorrect
class User {
// members
} // SyntaxError: expected ';' after class definition✅ Correct
class User {
// members
};Related C++ Tutorials & Compiler
C++ Inheritance, Virtual Functions, and Polymorphism
Derive subclasses, implement virtual functions, override base methods, and dynamic dispatch.
C++ Functions: Pass-by-Value, Pass-by-Reference, and Const
Understand function parameters, pass-by-value vs pass-by-reference (&), and const correctness.
C++ Exception Handling: try, catch, and std::exception
Catch and throw runtime exceptions safely using try, catch, and standard library exceptions.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.