Structures & OOP Basics

⚡ C++ Lesson 11 Intermediate

C++ was originally named "C with Classes". Object-Oriented Programming (OOP) is a key feature of C++, organizing programs around classes and objects.

1 Structs vs. Classes in C++

In C++, both structs and classes can contain member variables and methods. The only difference is their default access visibility:

  • struct: Members are **public** by default. Typically used for simple data structures containing no behaviors.
  • class: Members are **private** by default. Used for encapsulating data and logic.
2 Class Declarations

Let's run a program declaring classes and instantiating objects:

C++ — Classes and Objects ▶ Run Code
#include <iostream>
#include <string>

class Student {
private:
    std::string name;
    int age;

public:
    // Constructor to initialize fields
    Student(std::string name, int age) {
        this->name = name;
        this->age = age;
    }

    void displayInfo() {
        std::cout << "Student: " << name << ", Age: " << age << "\n";
    }
};

int main() {
    // Instantiate object using the 'new' stack allocation
    Student s1("Alice", 21);
    s1.displayInfo();

    return 0;
}
3 Code Challenge
Challenge: Write a class named `Car` with private fields: `brand` and `year`. Provide a public constructor and a public method called `drive()` printing "Driving brand!". Instantiate it in `main()` and call the method.