CIPHERCODE.AI · C++ OOP BEGINNER

C++ OOP beginner

Start from zero. Learn the words, install the compiler, then watch every line build objects in memory.

  • 6 modules
  • 5 live explanations
  • Definitions + quizzes

    You will be able to

    • Set up a compiler and run C++ programs
    • Explain OOP, classes, objects and the four pillars
    • Write classes with constructors, destructors and private data
    • Split code into header and source files

    How to use this page

    Press Run on a code block to see its output, then type it yourself. In every live explanation press Next (or Auto play) and watch the highlighted line, the typed explanation and the memory cards change together. Finish with the practice and the quiz, then mark the module complete to decode the cipher in the sphere.

    Module 1

    How to start: set up C++ and run your first program

    Understand what C++ is, install a compiler and compile your first file.

    About 90 minutes

    C++ is a general-purpose, compiled programming language created by Bjarne Stroustrup in 1979 as "C with Classes". Game engines, browsers, operating systems, embedded devices and trading systems use it because it is fast and gives you direct control over memory. C++ supports ordinary functions and also object-oriented programming (OOP), which is the subject of this whole course.

    Words you will meet today

    TermDefinitionExample
    Source codeThe text you write and save in a .cpp filemain.cpp
    CompilerA program that translates source code into machine code the computer can rung++, clang++, MSVC
    ExecutableThe final runnable file produced by the compilerapp or app.exe
    Editor / IDEThe tool where you type code. An IDE adds a compiler button and a debuggerVS Code, CLion, Code::Blocks
    Header fileA file of declarations, loaded with #include<iostream>
    Standard libraryReady-made code that ships with C++string, vector, cout

    Step 1: install a compiler

    SystemWhat to do
    WindowsInstall MSYS2 (msys2.org) and run pacman -S mingw-w64-ucrt-x86_64-gcc, or install Visual Studio Community and tick "Desktop development with C++".
    macOSOpen Terminal and run xcode-select --install.
    LinuxUbuntu or Debian: sudo apt install g++. Fedora: sudo dnf install gcc-c++.

    Check it worked: open a terminal and run g++ --version. If you see a version number, you are ready. No install yet? An online compiler such as onlinegdb.com runs the same code in your browser.

    Step 2: pick an editor

    Install VS Code (free) and make a folder called cpp-oop. Every file in this course goes in that folder.

    Step 3: write, compile, run

    Save this as main.cpp, press Run to preview the result, then do it yourself in the terminal.

    main.cpp
    #include <iostream>
    using namespace std;
    
    int main() {
        cout << "Hello, OOP!" << endl;
        return 0;
    }
    #include <iostream> copies in the tools for input and output. using namespace std; lets you write cout instead of std::cout. int main() is where every C++ program starts. cout << ... sends text to the screen and << is the insertion operator. endl ends the line. return 0; tells the operating system the program succeeded. Every statement ends with a semicolon.

    Compile and run it from the terminal:

    terminal
    g++ -std=c++17 -Wall main.cpp -o app
    ./app
    -std=c++17 picks the language version. -Wall turns on helpful warnings. -o app names the output file. On Windows run app.exe instead of ./app.
    StageWhat happens
    1. PreprocessLines starting with # are handled. #include pastes the header in.
    2. CompileYour C++ becomes machine-code pieces called object code.
    3. LinkThe pieces and library code are joined into one executable.

    Quick recap of C++ basics

    OOP builds on variables, input and output. Read this program, then run it.

    basics.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string name;
        int age;
        cout << "Name: ";
        cin >> name;
        cout << "Age: ";
        cin >> age;
        cout << "Hi " << name << ", next year you will be " << age + 1 << endl;
        return 0;
    }
    A variable is a named box in memory with a type. string name; reserves a box for text and int age; a box for a whole number. cin >> reads what the user types into the box. age + 1 is an expression that is calculated before printing.
    TypeHoldsExample
    intWhole numbersint age = 20;
    doubleDecimal numbersdouble price = 9.5;
    charOne characterchar grade = 'A';
    booltrue or falsebool ok = true;
    stringText (needs <string>)string city = "Pune";

    Key takeaways

    • C++ is compiled: source code goes through a compiler to make an executable
    • Compile with g++ -std=c++17 -Wall main.cpp -o app
    • main() is the entry point of every program
    • A variable has a type and a name; cin reads and cout prints

    Practice

    Write a program that asks for a city and prints I live in <city> on one line and OOP is fun on the next.

    Declare a string city, read it with cin, then use two cout lines with endl.

    city.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string city;
        cout << "City: ";
        cin >> city;
        cout << "I live in " << city << endl;
        cout << "OOP is fun" << endl;
        return 0;
    }

    Quick quiz

    What does the compiler do?

    Which command compiles main.cpp into a program named app?

    Module 2

    What is OOP? Definitions and the four pillars

    Learn the vocabulary before you write classes.

    About 75 minutes

    Object-oriented programming (OOP) is a way of designing programs around objects: things that bundle data (what they know) with functions (what they can do). Instead of thousands of loose variables and functions, you group them into small, self-contained pieces that model the real world: a Student, a BankAccount, a Car.

    Every object has three properties:

    • State: its data at this moment (a car's speed is 120).
    • Behaviour: what it can do (a car can honk or brake).
    • Identity: it is a separate thing, even if two objects hold the same values.

    Procedural versus object-oriented

    Procedural styleObject-oriented style
    Main ideaA list of functions that work on dataObjects that own their data and functions
    DataOften shared and globalHidden inside the object
    ReuseCopy and edit functionsInheritance and composition
    Good forSmall scripts and utilitiesLarge programs that keep growing

    The same idea in both styles. First the procedural version, then the OOP version you can run:

    procedural.cpp
    string carName = "BMW";
    int carSpeed = 120;
    
    void honk(string name) {
        cout << name << " says beep!";
    }
    // Ten cars means twenty loose variables.
    With many cars you must keep names and speeds in separate variables and pass the right one to every function. It is easy to mix them up.
    oop.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Car {
    public:
        string name;
        int speed;
        void honk() { cout << name << " says beep!" << endl; }
    };
    
    int main() {
        Car a;  a.name = "BMW";   a.speed = 120;
        Car b;  b.name = "Audi";  b.speed = 90;
        a.honk();
        b.honk();
        return 0;
    }
    The data (name, speed) and the action (honk) live together in Car. Each object a and b carries its own data, so there is no mix-up.

    The four pillars of OOP

    PillarDefinitionReal-life exampleC++ toolsLevel
    EncapsulationBundling data with the functions that use it and hiding the detailsA capsule: you take it without seeing the powder insideclass, private, gettersBeginner
    AbstractionShowing only what is needed and hiding how it worksA car pedal: you press it, you do not see the engineabstract classes, virtualIntermediate
    InheritanceA new class reuses and extends an existing classA Dog is an Animal, so it inherits eat() and sleep()class Dog : public AnimalIntermediate
    PolymorphismOne call, many behaviours depending on the objectspeak() sounds different for a Dog and a Catvirtual, overrideIntermediate

    Class versus object

    ClassObject
    Blueprint or templateReal thing built from the blueprint
    Written once in codeCreated many times at run time
    Uses no data memory by itselfEach object uses memory for its data
    "Car" as an idea"My red BMW" as a thing

    Key takeaways

    • OOP organises code around objects that hold state and behaviour
    • A class is a blueprint; an object is one real instance
    • The pillars are encapsulation, abstraction, inheritance and polymorphism
    • Find classes by looking for nouns and methods by looking for verbs

    Practice

    A library has books and members. Members borrow and return books. List the classes, their data and their methods.

    Nouns: Book, Member, Library. Verbs: borrow, return, add book.

    Book: title, author, isAvailable; methods markBorrowed(), markReturned().
    Member: name, id, list of borrowed books; methods borrow(book), returnBook(book).
    Library: list of books and members; methods addBook(), findBook(), checkout().

    Quick quiz

    Which pillar hides data inside a class?

    A class is best described as…

    Module 3

    Classes and objects

    Define a class, create objects and use the dot operator.

    About 2 hours

    Definitions

    TermMeaning
    ClassA user-defined type that groups data and functions: class Car { ... };
    Object (instance)A variable whose type is a class: Car c1;
    Data member (attribute)A variable declared inside a class: int speed;
    Member function (method)A function declared inside a class: void honk()
    Dot operator .Reaches a member of an object: c1.speed
    Arrow operator ->Reaches a member through a pointer: p->speed

    Step through the live explanation. The dashed card is the class and the green cards are objects in memory.

    A complete program

    students.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Student {
    public:
        string name;
        int marks;
    
        void show() {
            cout << name << " scored " << marks << endl;
        }
    };
    
    int main() {
        Student s1;
        s1.name = "Asha";
        s1.marks = 88;
    
        Student s2;
        s2.name = "Ravi";
        s2.marks = 74;
    
        s1.show();
        s2.show();
        return 0;
    }
    class Student { ... }; defines the type. public: means the members below can be used from anywhere (more in module 5). show() is a method that prints the object's own name and marks. In main, Student s1; creates the first object and the dot operator fills its data. s1.show() and s2.show() use the same code on different data.

    Under the hood: what happens in memory

    When the program reaches Student s1; the compiler reserves one block of memory for every data member. Methods are not copied into each object: all Students share one copy of show(), and each call is told which object to work on. A million objects cost a million sets of data, not a million copies of the code. You can check an object's size with sizeof(s1).

    Objects declared like Student s1; live on the stack and are destroyed automatically when their block ends. Objects made with new live on the heap and are covered in the Advanced file.

    struct or class?

    structclass
    Default accesspublicprivate
    Typical usePlain bundles of dataObjects that protect their data
    Everything elseIdentical: both can have methods, constructors and inheritance

    Key takeaways

    • A class is a blueprint, an object is a real instance
    • Data members hold state, member functions give behaviour
    • Use . on objects and -> on pointers to objects
    • Each object has its own data but all objects share the same method code

    Practice

    Write a Rectangle class with width and height and a method area() that returns width * height. Create two rectangles and print their areas.

    The method signature is int area() and it uses return width * height;.

    rect.cpp
    #include <iostream>
    using namespace std;
    
    class Rectangle {
    public:
        int width, height;
        int area() { return width * height; }
    };
    
    int main() {
        Rectangle r1; r1.width = 4; r1.height = 5;
        Rectangle r2; r2.width = 3; r2.height = 3;
        cout << r1.area() << " " << r2.area() << endl;
        return 0;
    }

    Quick quiz

    Where is the method code stored when you create 100 objects?

    What is the default access of members in a class?

    Module 4

    Constructors and destructors

    Set objects up correctly when they are born and clean up when they die.

    About 2 hours

    Definitions

    TermMeaningSyntax
    ConstructorA special method that runs automatically when an object is created. Same name as the class, no return typeCar() { }
    Default constructorTakes no argumentsCar() { speed = 0; }
    Parameterized constructorTakes arguments to set up the objectCar(string n, int s)
    Initializer listSets members before the body runs. Preferred styleCar(string n) : name(n) { }
    DestructorRuns automatically when an object is destroyed. Name starts with ~, no arguments~Car() { }

    Step through how a constructor builds two cars:

    Overloaded constructors with an initializer list

    box.cpp
    #include <iostream>
    using namespace std;
    
    class Box {
    public:
        int w, h;
        Box() : w(1), h(1) {}
        Box(int s) : w(s), h(s) {}
        Box(int a, int b) : w(a), h(b) {}
        void show() { cout << w << "x" << h << endl; }
    };
    
    int main() {
        Box a;
        Box b(5);
        Box c(3, 4);
        a.show();
        b.show();
        c.show();
        return 0;
    }
    Three constructors share one name but take different arguments. This is constructor overloading; the compiler chooses by the arguments you pass. : w(1), h(1) is an initializer list: it sets w and h directly instead of assigning inside the body. Box a; uses the default one, Box b(5) the one-argument version.

    Destructors

    A destructor runs when an object goes out of scope, so it is the right place to close files or release memory. Objects are destroyed in the reverse order of creation. Watch it happen:

    dtor.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Demo {
    public:
        string id;
        Demo(string s) { id = s; cout << id << " created" << endl; }
        ~Demo() { cout << id << " destroyed" << endl; }
    };
    
    int main() {
        Demo a("A");
        Demo b("B");
        cout << "working" << endl;
        return 0;
    }
    Both objects are created at the top of main and destroyed automatically at the closing brace, last created first. You never call a destructor yourself for stack objects.

    Key takeaways

    • A constructor has the class name and no return type; a destructor has ~ and no arguments
    • Overload constructors to allow different ways of creating objects
    • Prefer initializer lists: Car(string n) : name(n) {}
    • Destructors run automatically, in reverse order of construction

    Practice

    Make a Book class with title and pages. Add a default constructor (title "Unknown", pages 0) and a parameterized one. Print both books.

    Use an initializer list in both constructors: Book() : title("Unknown"), pages(0) {}.

    book.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Book {
    public:
        string title;
        int pages;
        Book() : title("Unknown"), pages(0) {}
        Book(string t, int p) : title(t), pages(p) {}
        void show() { cout << title << " (" << pages << " pages)" << endl; }
    };
    
    int main() {
        Book a;
        Book b("C++ OOP", 320);
        a.show();
        b.show();
        return 0;
    }

    Quick quiz

    What is the return type of a constructor?

    Three objects a, b, c are created in that order in main. In which order are they destroyed?

    Module 5

    Encapsulation: public, private and getters

    Protect your data so only safe code can change it.

    About 2 hours

    Definitions

    TermMeaning
    EncapsulationBundling data and the functions that use it in one class, and controlling access to the data
    Access specifierA keyword that sets who can use a member: public, private, protected
    Getter (accessor)A public method that reads a private member
    Setter (mutator)A public method that changes a private member after checking it
    InvariantA rule that must always be true, such as "balance is never negative"
    SpecifierWho can use the member
    publicAny code, anywhere
    privateOnly functions of the same class
    protectedThe class and its derived classes (inheritance, Intermediate file)

    Watch how a private member is protected, and what the compiler says when you try to break the rule:

    A safe bank account

    bank.cpp
    #include <iostream>
    using namespace std;
    
    class BankAccount {
    private:
        double balance;
    public:
        BankAccount(double start) { balance = start > 0 ? start : 0; }
    
        void deposit(double amt) {
            if (amt > 0) balance += amt;
        }
        bool withdraw(double amt) {
            if (amt > 0 && amt <= balance) {
                balance -= amt;
                return true;
            }
            return false;
        }
        double getBalance() const { return balance; }
    };
    
    int main() {
        BankAccount acc(100);
        acc.deposit(50);
        cout << acc.withdraw(500) << endl;
        cout << acc.withdraw(30) << endl;
        cout << acc.getBalance() << endl;
        return 0;
    }
    balance is private, so main cannot write acc.balance = 1000000. The constructor refuses a negative start. deposit and withdraw check the rules every time, so the invariant "balance is never negative" cannot be broken from outside. withdraw(500) returns false (printed as 0) because 500 is more than 150. withdraw(30) succeeds (1) and the balance becomes 120. The trailing const on getBalance promises it does not change the object.

    Key takeaways

    • private data can only be used by the class's own functions
    • Getters read, setters validate and then write
    • Encapsulation protects invariants
    • Mark read-only methods const

    Practice

    Write a Student class with a private marks. Add setMarks(int) that ignores values below 0 or above 100, and getMarks(). Test both from main.

    Check if (m >= 0 && m <= 100) before assigning inside setMarks.

    student.cpp
    #include <iostream>
    using namespace std;
    
    class Student {
        int marks = 0;
    public:
        void setMarks(int m) { if (m >= 0 && m <= 100) marks = m; }
        int getMarks() const { return marks; }
    };
    
    int main() {
        Student s;
        s.setMarks(95);
        s.setMarks(250);
        cout << s.getMarks() << endl;
        return 0;
    }

    Quick quiz

    Why make data members private?

    What does a trailing const on a method mean?

    Module 6

    Methods outside the class, the this pointer and const

    Organise code like real C++ projects.

    About 2 hours

    1. Define methods outside the class

    Large classes become hard to read. Declare the method inside the class and write its body outside using the scope resolution operator ::, which means "this function belongs to that class". In real projects the class goes in a header (Car.h) and the bodies in Car.cpp.

    Car.h
    #pragma once
    #include <string>
    
    class Car {
        std::string name;
        int speed;
    public:
        Car(std::string n, int s);
        void honk() const;
    };
    The header only declares what the class has. #pragma once stops it being included twice. Headers use std::string instead of using namespace std;.
    Car.cpp
    #include "Car.h"
    #include <iostream>
    
    Car::Car(std::string n, int s) : name(n), speed(s) {}
    
    void Car::honk() const {
        std::cout << name << " says beep!" << std::endl;
    }
    Car::Car defines the constructor and Car::honk defines the method. Compile every .cpp together: g++ main.cpp Car.cpp -o app. Quotes in #include "Car.h" mean "my own header".

    2. The this pointer

    this is a hidden pointer available inside every non-static method. It points to the object the method was called on. It resolves name clashes and lets a method return its own object so calls can be chained. Step through it:

    person.cpp
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Person {
        string name;
    public:
        Person(string name) { this->name = name; }
        void show() const { cout << "I am " << name << endl; }
    };
    
    int main() {
        Person p("Asha");
        p.show();
        return 0;
    }
    The parameter and the member are both called name. Inside the constructor plain name means the parameter, so this->name picks the member. It reads: "the name of this object equals the argument".

    3. const methods and const objects

    A method marked const cannot change data members. A const object can only call const methods. Mark every getter const.

    Common compile errors and how to fix them

    Compiler messageCauseFix
    expected ';' after class definitionMissing semicolon after the closing braceWrite };
    'x' is private within this contextUsing a private member from outsideAdd a public getter or setter
    no matching function for call to 'Car::Car()'Only a parameterized constructor existsPass arguments or add a default constructor
    'string' does not name a typeMissing #include <string> or std::Add the include and use std::string
    undefined reference to 'Car::honk()'Method declared but .cpp not compiled or body missingCompile every .cpp file and write the body
    passing 'const Car' as 'this' discards qualifiersCalling a non-const method on a const objectMark the method const

    Key takeaways

    • Class::method defines a method outside the class
    • Headers declare, .cpp files define; compile all .cpp files together
    • this points to the current object; *this is the object itself
    • const methods promise not to change the object

    Practice

    Split a Counter class (with increment() and get() const) into Counter.h, Counter.cpp and main.cpp, then compile all three.

    The header holds the class with declarations only; Counter.cpp includes the header and defines Counter::increment.

    Compile with g++ -std=c++17 main.cpp Counter.cpp -o app. If you see undefined reference, you forgot to list Counter.cpp.

    Quick quiz

    What does this point to inside a method?

    What does Car::honk mean?

    REVISION · BEGINNER

    Definition bank and exam-style questions

    Learn each definition in one sentence. In written exams define the term first, then add a short example if asked.

    Beginner C++ OOP definitions

    Object-oriented programming
    A style of programming that organises code into objects holding data and behaviour.
    Class
    A user-defined type that acts as a blueprint for objects.
    Object / instance
    A real value of a class type that occupies memory.
    Data member
    A variable declared inside a class.
    Member function / method
    A function declared inside a class that works on its objects.
    Constructor
    A special method that initialises an object when it is created.
    Destructor
    A special method that runs when an object is destroyed.
    Initializer list
    The colon list after a constructor header that initialises members directly.
    Encapsulation
    Bundling data with functions and restricting direct access to the data.
    Access specifier
    Keyword (public, private, protected) that controls who can use a member.
    this pointer
    A hidden pointer to the object on which a non-static method was called.
    Scope resolution operator
    The :: operator that names the class or namespace a name belongs to.
    const method
    A method that promises not to modify the object.
    Stack
    Fast memory where local variables and objects are created and automatically destroyed.
    Header file
    A file of declarations (.h or .hpp) shared with #include.
    Compiler
    A program that translates C++ source code into machine code.

    Exam-style questions with answers

    Q1. What is the difference between a class and an object?

    Answer: A class is a blueprint that defines data and functions. An object is a real instance of the class that occupies memory. One class can have many objects, each with its own data.

    Q2. What is a constructor? Can it be overloaded?

    Answer: A constructor is a special member function with the class name and no return type that runs automatically when an object is created. Yes, it can be overloaded by giving different parameter lists.

    Q3. What is the difference between struct and class in C++?

    Answer: Default access: struct members are public, class members are private. Everything else is the same.

    Q4. When is a destructor called?

    Answer: When an object goes out of scope, or when delete is used on a heap object. Local objects are destroyed in reverse order of creation.

    Q5. What is encapsulation and why is it useful?

    Answer: It is bundling data with the functions that operate on it and hiding the data behind public methods. It protects invariants and lets you change internals without breaking users of the class.

    Q6. What is the this pointer?

    Answer: A pointer to the current object, passed implicitly to non-static member functions. It is used to resolve name conflicts and to return the object for chaining.

    Practical assignments

    1. Create a Student class with private data, a constructor, getters and a validating setter.
    2. Create a BankAccount with deposit, withdraw and a rule that balance never goes negative.
    3. Split a class into a .h and a .cpp file and compile them together.
    4. Print a message in a constructor and destructor and predict the output order before running.
    5. Create an array of five objects and print each one.

    Beginner complete

    Next: inheritance, polymorphism and abstract classes.

    Open Intermediate