C++:C++ Classes and Object-Oriented Programming (OOP)
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:

ParameterTypeDescription
privateAccess SpecifierAccessible only within class member methods.
publicAccess SpecifierAccessible to external callers and instances.
Member Initializer ListConstructor Syntax: member(value) sets state before constructor body.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler