Menu
Coddy logo textTech

Classes vs Objects

Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 6 of 104.

A class is a blueprint that defines structure. An object is a specific instance created from that blueprint.

The class (blueprint)

class Car {
public:
    std::string brand;
    int year;
    
    std::string getInfo() {
        return brand + " (" + std::to_string(year) + ")";
    }
};

Creating multiple objects (instances)

Car car1;
car1.brand = "Tesla";
car1.year = 2023;

Car car2;
car2.brand = "Honda";
car2.year = 2020;

std::cout << car1.getInfo() << std::endl;  // Tesla (2023)
std::cout << car2.getInfo() << std::endl;  // Honda (2020)

Each object is independent. Changing car1 doesn't affect car2. You can create multiple objects from the same class, each holding its own data.

challenge icon

Challenge

Medium

Create a Car class (blueprint). The program creates two separate objects (instances) from it, each with its own data:

  • Public members: brand (string), year (int)
  • getInfo() — returns "<brand> (<year>)"

Cheat sheet

A class is a blueprint that defines structure. An object is a specific instance created from that blueprint.

Defining a class:

class Car {
public:
    std::string brand;
    int year;
    
    std::string getInfo() {
        return brand + " (" + std::to_string(year) + ")";
    }
};

Creating objects from a class:

Car car1;
car1.brand = "Tesla";
car1.year = 2023;

Car car2;
car2.brand = "Honda";
car2.year = 2020;

std::cout << car1.getInfo() << std::endl;  // Tesla (2023)
std::cout << car2.getInfo() << std::endl;  // Honda (2020)

Each object is independent and holds its own data. Changing one object doesn't affect another.

Try it yourself

#include <iostream>
#include "Car.h"

int main() {
    std::string brand1, brand2;
    int year1, year2;
    
    std::getline(std::cin, brand1);
    std::cin >> year1;
    std::cin.ignore();
    std::getline(std::cin, brand2);
    std::cin >> year2;
    
    Car car1;
    car1.brand = brand1;
    car1.year = year1;
    
    Car car2;
    car2.brand = brand2;
    car2.year = year2;
    
    std::cout << "Car 1: " << car1.getInfo() << std::endl;
    std::cout << "Car 2: " << car2.getInfo() << std::endl;
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming