C++OOPbeginner

C++ Classes and Objects for Beginners

Learn what a class and an object are in C++, write a class with data and member functions, create objects and protect data with private.

Published
TL;DR – Quick Answer

A class in C++ is a user-defined type that groups data (data members) and the functions that work on that data (member functions). An object is a variable of that class type. You define a class with the class keyword, create objects such as Rectangle r1;, and use the dot operator to reach members, as in r1.area(). Keeping data private and functions public protects the object from wrong values.

On This Page

C++ adds object-oriented programming (OOP) on top of C, and classes and objects are where OOP starts. A class lets you create your own type that holds both data and the functions that work on that data. An object is a variable of that type.

This page builds a few simple classes step by step and shows the output of each program. It assumes you know basic C++ syntax such as cout, which is covered in the C++ tutorial for beginners.

Class and object: the idea

A class is a blueprint. An object is a real thing made from it.

Class (blueprint) Data it describes Things it can do Objects
Rectangle length, width find area, find perimeter a 5 x 3 rectangle, a 4 x 4 square
Student roll, name, marks show details, update marks Anjali, Kiran
BankAccount owner, balance deposit, withdraw Meena's account

In C, a structure can only hold data, and you write separate functions to work on it. A C++ class keeps the data and its functions together in one unit. This idea is called encapsulation.

Your first class in C++

#include <iostream>
using namespace std;

class Rectangle {
public:
    int length;
    int width;

    int area() {
        return length * width;
    }

    int perimeter() {
        return 2 * (length + width);
    }
};

int main() {
    Rectangle r1;
    r1.length = 5;
    r1.width = 3;

    Rectangle r2;
    r2.length = 4;
    r2.width = 4;

    cout << "r1 area: " << r1.area() << ", perimeter: " << r1.perimeter() << "\n";
    cout << "r2 area: " << r2.area() << ", perimeter: " << r2.perimeter() << "\n";
    return 0;
}

Output:

r1 area: 15, perimeter: 16
r2 area: 16, perimeter: 16
Part Meaning
class Rectangle { ... }; Defines a new type called Rectangle. Note the ; at the end
public: The members below can be used from outside the class, for example in main
int length; int width; Data members: the data each object holds
int area() A member function: code that works on the object's data
Rectangle r1; Creates an object called r1
r1.length = 5; The dot operator reaches a member of an object

Inside area(), length and width mean "this object's length and width". When you call r1.area(), it uses r1's values. When you call r2.area(), it uses r2's values.

Each object has its own data

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

class Counter {
public:
    string label;
    int count = 0;

    void click() {
        count++;
    }
};

int main() {
    Counter a, b;
    a.label = "Likes";
    b.label = "Shares";

    a.click();
    a.click();
    a.click();
    b.click();

    cout << a.label << ": " << a.count << "\n";
    cout << b.label << ": " << b.count << "\n";
    return 0;
}

Output:

Likes: 3
Shares: 1

a and b are two objects of the same class, but each has its own count. Clicking a does not change b. The = 0 after int count gives every new object a starting value. This style needs C++11 or later, which every current compiler supports.

Access specifiers: public and private

So far every member was public, so any code could change it. That is risky. Nothing stops r1.length = -5;.

Access specifier Who can use the member
public Any code
private Only member functions of the same class
protected The class and classes that inherit from it

The usual pattern is: data private, functions public. Outside code changes data only through functions that check the values first.

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

class Student {
private:
    string name;
    int marks;

public:
    void setData(string n, int m) {
        name = n;
        if (m >= 0 && m <= 100) {
            marks = m;
        } else {
            marks = 0;
            cout << "Invalid marks for " << n << ", set to 0\n";
        }
    }

    int getMarks() {
        return marks;
    }

    void show() {
        cout << name << " scored " << marks << "\n";
    }
};

int main() {
    Student s1, s2;
    s1.setData("Anjali", 88);
    s2.setData("Kiran", 140);

    s1.show();
    s2.show();
    cout << "Total: " << s1.getMarks() + s2.getMarks() << "\n";
    return 0;
}

Output:

Invalid marks for Kiran, set to 0
Anjali scored 88
Kiran scored 0
Total: 88

If you try s1.marks = 50; in main, the compiler stops with an error saying that marks is private. That is the point. setData is the only way in, and it rejects marks above 100. Functions like getMarks that only return a value are often called getters, and functions that set a value are called setters.

Defining member functions outside the class

For longer functions, declare them inside the class and write the body outside using the scope resolution operator ::.

#include <iostream>
using namespace std;

class Circle {
private:
    double radius;

public:
    void setRadius(double r);
    double area();
};

void Circle::setRadius(double r) {
    radius = r;
}

double Circle::area() {
    return 3.14 * radius * radius;
}

int main() {
    Circle c;
    c.setRadius(10);
    cout << "Area: " << c.area() << "\n";
    return 0;
}

Output:

Area: 314

Circle::area means "the area function that belongs to Circle". Without Circle::, the compiler would treat it as an ordinary function that cannot see radius.

cout prints the double value 314.0 as 314 because it drops trailing zeros by default. Large projects put the class definition in a header file (circle.h) and the function bodies in a source file (circle.cpp), which is why this style is common.

Array of objects

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

class Product {
public:
    string name;
    int price;
    int qty;

    int total() {
        return price * qty;
    }
};

int main() {
    Product cart[3] = {
        {"Notebook", 45, 4},
        {"Pen", 10, 5},
        {"Bag", 650, 1}
    };
    int bill = 0;

    for (int i = 0; i < 3; i++) {
        cout << cart[i].name << ": " << cart[i].total() << "\n";
        bill += cart[i].total();
    }
    cout << "Bill: " << bill << "\n";
    return 0;
}

Output:

Notebook: 180
Pen: 50
Bag: 650
Bill: 880

cart[i] is one object, and cart[i].total() calls that object's function. The brace lists like {"Notebook", 45, 4} work here because every data member is public and the class has no constructor. With private data, you use a constructor instead, which is the topic of constructors and destructors in C++.

The this pointer

Inside a member function, this is a pointer to the object that called the function. You need it when a parameter has the same name as a data member.

class Box {
private:
    int size;
public:
    void setSize(int size) {
        this->size = size;   // left: the member, right: the parameter
    }
};

Without this->, size = size; would assign the parameter to itself and leave the member unchanged.

class vs struct in C++

Point class struct
Default access private public
Can have member functions Yes Yes
Can have constructors, inheritance Yes Yes
Common use Objects with behaviour and protected data Simple groups of public data

In C++, the default access is the only real difference. A C struct, by contrast, cannot have member functions at all. See C vs C++ for the other differences between the two languages.

Common mistakes with classes

Mistake What happens Fix
Missing ; after the class Confusing errors on the next line End with };
Using a private member in main Compile error: member is private Add a public function, or rethink the design
Forgetting ClassName:: outside the class Function cannot see the data members Write void Circle::setRadius(double r)
Calling a function without the object area(); in main gives an error Call it on an object: r1.area()
Leaving data members without a value They hold garbage values Give default values or use a constructor
Making everything public Any code can set wrong values Keep data private and check values in setters

Quick revision

  1. A class is a blueprint. An object is a variable made from it.
  2. A class holds data members and member functions.
  3. Use the dot operator to reach members: r1.area().
  4. Class members are private by default. Struct members are public.
  5. Keep data private and give public functions to read and change it.
  6. Define functions outside the class with ClassName::function.

The next step is to set up an object correctly the moment it is created. That is the job of a constructor. Read C++ constructors and destructors, then practise with the OOPs interview questions and the C++ interview questions for freshers.

Frequently Asked Questions

What is a class and object in C++ in simple words?
A class is a blueprint, like the plan of a house. An object is one real house built from that plan. One class can be used to create many objects, and each object has its own copy of the data.
Does a class take memory in C++?
The class definition itself does not hold data. Memory for data members is set aside when you create an object. Member functions are stored once and shared by all objects.
What is the default access specifier in a C++ class?
Members of a class are private by default. Members of a struct are public by default. That is the only difference between class and struct in C++.
What is a member function?
A member function is a function declared inside a class. It can use the object's data members directly, without passing them as arguments.
What is the scope resolution operator in C++?
The :: operator tells the compiler which class a name belongs to. When you define a member function outside the class, you write ClassName::functionName so the compiler knows it belongs to that class.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Discover CodeBegun's Java Full Stack track

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 5 December 2026 LinkedIn
Chat with us