Lesson 9 of 20Core Programming22 min

Classes and Objects

A class defines a new type. An object is an individual instance of that class. Classes allow related data and functions to be kept together.

Create a Class

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

class Student
{
public:
    string name;
    int age;

    void display() const
    {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main()
{
    Student student;
    student.name = "Alice";
    student.age = 20;
    student.display();

    return 0;
}

Class and Object

TermMeaning
ClassA blueprint that defines data and behaviour.
ObjectA usable instance created from a class.
Member variableA value stored inside an object.
Member functionA function that belongs to the class.
Practice task

Create a Product class with a name, price, and a function that displays both values.

Lesson Summary

Create your first class and use objects to combine data with behaviour.