HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Classes (OOP)

Classes (OOP)

class, public members, constructor, methods and object creation.

Simple enough for a 5-year-old to understand

class and constructor

Example code
1
#include <iostream>
2
#include <string>
3
using namespace std;
4
class Cat {
Class.
DefinitionClass.
5
public:
Members accessible from outside.
DefinitionMembers accessible from outside.
6
string name;
Field.
VariableField.
7
Cat(string a) { name = a; }
Constructor.
FunctionConstructor.
8
string meow() { return name + ": meow"; }
Method.
FunctionMethod.
9
};
End of class — ends with ;!
DefinitionEnd of class — ends with ;!
10
int main() {
11
Cat k("Tabby");
Create an object.
CodeCreate an object.
12
cout << k.meow() << endl;
Tekir: meow
Output / InputTekir: meow
13
return 0;
14
}
DefinitionVariableFunctionCodeOutput / Input
💡 Hint: Don't forget to put a ; after the class definition: class X { ... };

About this topic

A class combines data and the functions that process that data into a single type. The goal is not just organization, but restricting access: the internal state of the object cannot be modified directly from the outside, but only through the functions provided by the class.

The value of this constraint is this: when a field falls into an invalid value, instead of hunting for the culprit, you only look at the single place that writes to that field. If a field is public, as the program grows, it becomes impossible to figure out which code broke it.

C++'s distinguishing feature in this regard is the destructor: it is called automatically when the object goes out of scope. This is the foundation of C++'s resource management principle — resources like files, memory, or connections are tied to the lifetime of the object, and you cannot forget to release them manually.

What you will learn

  • Defining classes and creating objects
  • public and private access specifiers
  • When the constructor is called
  • Why the destructor is important
  • The difference between class and struct

Who is this for?

  • Those who want to learn object-oriented design in C++
  • Those who want to automate resource management
  • Those looking for code organization in large projects

When to use?

A class is used when there is data that carries meaning together and operations that work on that data. For simple structures that only carry data, a struct is sufficient.

If you need to open and close a resource, put the opening in the constructor and the closing in the destructor. Thus, even if an exception is thrown, the resource is released; this is C++'s most powerful idiom.

Common mistakes

Wrong

#include <iostream>
using namespace std;

class Person {
    string name;
public:
    void show() {
        cout << name << endl;
    }
};

int main() {
    Person p;
    p.name = "Ali";
    p.show();
    return 0;
}

Fields defined inside a class without an access specifier become private, so the name field cannot be accessed from inside main and the compiler gives the error "'name' is private within this context". In a struct, the default is public; that is the only difference.

Correct

#include <iostream>
#include <string>
using namespace std;

class Person {
    string name;
public:
    Person(string n) : name(n) {}
    void show() {
        cout << name << endl;
    }
};

int main() {
    Person p("Ali");
    p.show();
    return 0;
}

Wrong

#include <iostream>
using namespace std;

class Counter {
    int value;
public:
    void increase() {
        value++;
    }
    int get() {
        return value;
    }
};

int main() {
    Counter c;
    c.increase();
    cout << c.get() << endl;
    return 0;
}

value was never initialized; class members, just like local variables, are not automatically initialized either. The result of the increment depends on the garbage value in memory and can change on every run. Members must be initialized in the constructor or at definition.

Correct

#include <iostream>
using namespace std;

class Counter {
    int value = 0;
public:
    void increase() {
        value++;
    }
    int get() const {
        return value;
    }
};

int main() {
    Counter c;
    c.increase();
    cout << c.get() << endl;
    return 0;
}

Wrong

#include <iostream>
using namespace std;

class Box {
    int *data;
public:
    Box() {
        data = new int[100];
    }
};

int main() {
    Box b;
    cout << "Finished" << endl;
    return 0;
}

The constructor allocated memory but there is no destructor to release it; when the object is destroyed, memory leaks. This is not visible in this small program, but in code that creates objects inside a loop, memory consumption continuously increases. The rule that the code which allocates is also responsible for releasing is enforced here by the destructor.

Correct

#include <iostream>
#include <vector>
using namespace std;

class Box {
    vector<int> data;
public:
    Box() : data(100) {}
};

int main() {
    Box b;
    cout << "Finished" << endl;
    return 0;
}

Frequently asked questions

What is the difference between class and struct?

The only difference is the default access level: private in a class, public in a struct. Technically there are no other differences. By convention, struct is used for simple types that only carry data, while class is used for types that also include behavior.

What does const at the end of a member function mean?

It declares that this function does not modify the state of the object. If you attempt to modify it, you will get a compilation error. Furthermore, only functions marked this way can be called on a const object, which is why it must be written on getter functions.

Why is it recommended not to manage memory manually?

Because types like vector and smart pointers do this for you without errors. Managing allocation with new and release with delete manually leads to leaks when exceptions are thrown or early returns are made. In Modern C++, you rarely need to write new.

Summary

A class combines data and behavior, restricting access with private.

Members are not initialized automatically; they must be initialized at definition or in the constructor.

The destructor automatically releases resources when the object goes out of scope.

The only difference between class and struct is the default access level.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code