Tutorials Logic, IN info@tutorialslogic.com

C++ Classes and Objects: Detailed Notes, Syntax, Examples & FAQs

What is a Class in C++?

A class in C++ is a user-defined type that groups data members and member functions.

An object is an instance of a class. It has its own copy of non-static data members.

Classes and objects are the base of C++ object-oriented programming, but this page focuses only on class syntax, object creation, members, constructors, destructors, object lifetime, static members, and access rules.

A class is a blueprint for creating objects. It describes what data an object stores and what operations can be performed on that data.

In C++, a class can contain variables, functions, constructors, destructors, static members, constants, and access specifiers. The most common use is to keep related data and behavior together in one named type.

  • A class is declared using the class keyword.
  • Data inside a class is called data members or fields.
  • Functions inside a class are called member functions or methods.
  • A semicolon is required after the closing brace of a class.
  • By default, class members are private in C++.

Basic Class Syntax

Basic Class Syntax
class Student {
private:
    int rollNo;
    double marks;

public:
    void setData(int r, double m) {
        rollNo = r;
        marks = m;
    }

    void display() {
        cout << rollNo << " " << marks << endl;
    }
};

What is an Object?

An object is a real variable created from a class. If a class is a blueprint, an object is the actual item built from that blueprint.

Each object has its own non-static data. For example, two Student objects can have different roll numbers and marks, even though they come from the same Student class.

  • Objects are created using the class name followed by an object name.
  • Use the dot operator (.) to access public members through an object.
  • Private members cannot be accessed directly from outside the class.
  • Different objects of the same class store different values.

Creating and Using Objects

Creating and Using Objects
#include <iostream>
using namespace std;

class Student {
private:
    int rollNo;
    double marks;

public:
    void setData(int r, double m) {
        rollNo = r;
        marks = m;
    }

    void display() {
        cout << "Roll No: " << rollNo << ", Marks: " << marks << endl;
    }
};

int main() {
    Student s1;
    Student s2;

    s1.setData(101, 87.5);
    s2.setData(102, 91.0);

    s1.display();
    s2.display();

    return 0;
}

Class and Object Difference

The class itself is only the plan. Memory for normal data members is allocated when objects are created from that class.

Class Object
Blueprint or user-defined type Instance of a class
Does not store actual per-object values by itself Stores actual values in memory
Declared once Can be created many times
Example: class Student Example: Student s1

Access Specifiers

Access specifiers control where class members can be used. They help protect data and expose only the functions that outside code should use.

Specifier Accessible From Common Use
private Only inside the same class Hide data members
public Anywhere the object is visible Expose methods like setData() and display()
protected Same class and derived classes Used mainly with inheritance

Data Members and Member Functions

Data members represent the state of an object. Member functions represent the behavior of an object. Good class design keeps data private and provides public functions to read or modify that data safely.

  • Data members should usually be private.
  • Member functions can validate input before changing data.
  • Getter functions return data.
  • Setter functions update data after checking rules.
  • A const member function promises not to modify the object.

Getters, Setters, and const Member Function

Getters, Setters, and const Member Function
#include <iostream>
#include <string>
using namespace std;

class Product {
private:
    string name;
    double price;

public:
    void setName(string n) {
        name = n;
    }

    void setPrice(double p) {
        if (p >= 0) {
            price = p;
        }
    }

    string getName() const {
        return name;
    }

    double getPrice() const {
        return price;
    }
};

int main() {
    Product p;
    p.setName("Keyboard");
    p.setPrice(1200);

    cout << p.getName() << " costs " << p.getPrice() << endl;
    return 0;
}

Defining Member Functions Outside the Class

For small functions, writing the body inside the class is fine. For larger functions, declare the function inside the class and define it outside using the scope resolution operator (::).

  • Declaration tells the compiler the function exists.
  • Definition contains the actual function body.
  • Use ClassName::functionName to define a member function outside the class.

Function Definition Outside Class

Function Definition Outside Class
#include <iostream>
using namespace std;

class Rectangle {
private:
    int length;
    int width;

public:
    void setDimensions(int l, int w);
    int area() const;
};

void Rectangle::setDimensions(int l, int w) {
    length = l;
    width = w;
}

int Rectangle::area() const {
    return length * width;
}

int main() {
    Rectangle r;
    r.setDimensions(10, 5);
    cout << "Area = " << r.area() << endl;
    return 0;
}

Constructors in Classes

A constructor is a special member function that runs automatically when an object is created. It is used to initialize data members.

  • Constructor name is the same as the class name.
  • Constructor has no return type.
  • A default constructor takes no arguments.
  • A parameterized constructor takes arguments.
  • Initializer lists are preferred for initializing data members.

Default and Parameterized Constructors

Default and Parameterized Constructors
#include <iostream>
using namespace std;

class Point {
private:
    int x;
    int y;

public:
    Point() : x(0), y(0) {}

    Point(int xValue, int yValue) : x(xValue), y(yValue) {}

    void print() const {
        cout << "(" << x << ", " << y << ")" << endl;
    }
};

int main() {
    Point p1;
    Point p2(3, 4);

    p1.print();
    p2.print();

    return 0;
}

Destructors and Object Lifetime

A destructor is a special member function that runs automatically when an object is destroyed. It is commonly used to release resources such as dynamic memory, file handles, or network connections.

For normal stack objects, the destructor runs when the object goes out of scope. For dynamically allocated objects created with new, the destructor runs when delete is used.

  • Destructor name is the class name with a tilde prefix, for example ~FileHandler().
  • A destructor has no return type and takes no parameters.
  • Only one destructor is allowed in a class.
  • If a class does not manage external resources, the compiler-generated destructor is usually enough.

Constructor and Destructor Flow

Constructor and Destructor Flow
#include <iostream>
using namespace std;

class Demo {
public:
    Demo() {
        cout << "Constructor called" << endl;
    }

    ~Demo() {
        cout << "Destructor called" << endl;
    }
};

int main() {
    Demo d;
    cout << "Inside main" << endl;
    return 0;
}

Classes And Objects Expected Output

Classes And Objects Expected Output
Constructor called
Inside main
Destructor called

Object Creation Methods

Objects can be created in different ways depending on lifetime and memory needs.

Creation Style Example Notes
Stack object Student s1; Destroyed automatically when scope ends
Parameterized object Point p(3, 4); Calls matching constructor
Pointer to object Student* ptr = &s1; Uses -> to access public members
Dynamic object Student* p = new Student(); Must be deleted manually unless using smart pointers

Object Pointer and Dynamic Object

Object Pointer and Dynamic Object
#include <iostream>
using namespace std;

class Demo {
public:
    void show() {
        cout << "Object function called" << endl;
    }
};

int main() {
    Demo d;
    d.show();       // dot operator

    Demo* ptr = &d;
    ptr->show();    // arrow operator

    Demo* heapObj = new Demo();
    heapObj->show();
    delete heapObj;

    return 0;
}

Array and Vector of Objects

A class is a type, so you can create arrays or vectors of objects the same way you create arrays or vectors of int, double, or string values.

Arrays of objects are useful when the number of objects is fixed. Vectors are usually better when the number of objects can grow or shrink.

  • Each element in an object array is a separate object.
  • If you create an array with default syntax, the class needs a default constructor.
  • Use vector<ClassName> for flexible collections of objects.
  • Use range-based for loops to read or display all objects cleanly.

Vector of Student Objects

Vector of Student Objects
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Student {
private:
    string name;
    int marks;

public:
    Student(string studentName, int studentMarks)
        : name(studentName), marks(studentMarks) {}

    void display() const {
        cout << name << " scored " << marks << endl;
    }
};

int main() {
    vector<Student> students = {
        Student("Asha", 88),
        Student("Ravi", 92),
        Student("Neha", 85)
    };

    for (const Student& student : students) {
        student.display();
    }

    return 0;
}

Static Data Members

A normal data member belongs to each object. A static data member belongs to the class itself and is shared by all objects.

  • Static data members are declared inside the class.
  • They must be defined outside the class before C++17 inline variables.
  • Static member functions can be called using ClassName::functionName().
  • Static member functions cannot directly access non-static data members.

Counting Objects with static Member

Counting Objects with static Member
#include <iostream>
using namespace std;

class Counter {
private:
    static int count;

public:
    Counter() {
        count++;
    }

    static int getCount() {
        return count;
    }
};

int Counter::count = 0;

int main() {
    Counter c1, c2, c3;
    cout << "Objects created: " << Counter::getCount() << endl;
    return 0;
}

Copying Objects

When one object is initialized from another object of the same class, C++ copies the data members. For simple classes that contain int, double, string, or other safe value types, the default copy behavior is usually fine.

When a class owns raw dynamic memory or another resource, copying needs extra care. In that case, define proper copy behavior or prefer standard library types that manage memory safely.

  • Object copying can happen during initialization, assignment, or function calls by value.
  • Passing large objects by const reference avoids unnecessary copies.
  • For beginner class examples, prefer string, vector, and other standard library members instead of raw pointers.

Object Copy Example

Object Copy Example
#include <iostream>
#include <string>
using namespace std;

class Book {
private:
    string title;

public:
    Book(string bookTitle) : title(bookTitle) {}

    void show() const {
        cout << title << endl;
    }
};

int main() {
    Book b1("C++ Basics");
    Book b2 = b1;

    b1.show();
    b2.show();

    return 0;
}

this Pointer

Inside a non-static member function, this is a pointer to the current object. It is useful when parameter names match data member names or when returning the current object.

  • this->member accesses the current object member.
  • this is available only inside non-static member functions.
  • Returning *this enables method chaining.

Using this Pointer

Using this Pointer
#include <iostream>
using namespace std;

class Box {
private:
    int length;

public:
    Box& setLength(int length) {
        this->length = length;
        return *this;
    }

    void show() const {
        cout << "Length = " << length << endl;
    }
};

int main() {
    Box b;
    b.setLength(10).show();
    return 0;
}

Complete Class and Object Example

This example combines private data, constructor, setters, getters, const function, object creation, and method calls.

BankAccount Class Example

BankAccount Class Example
#include <iostream>
#include <string>
using namespace std;

class BankAccount {
private:
    string owner;
    double balance;

public:
    BankAccount(string ownerName, double openingBalance)
        : owner(ownerName), balance(openingBalance) {}

    string getOwner() const {
        return owner;
    }

    double getBalance() const {
        return balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    bool withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }

    void display() const {
        cout << owner << " balance: " << balance << endl;
    }
};

int main() {
    BankAccount account("Ravi", 5000);

    account.deposit(1500);
    account.withdraw(700);
    account.display();

    return 0;
}

Classes And Objects Expected Output 2

Classes And Objects Expected Output 2
Ravi balance: 5800
Before you move on

C++ Classes and Objects: Detailed Notes, Syntax, Examples & FAQs Mastery Check

5 checks
  • A class is a blueprint for creating objects.
  • It describes what data an object stores and what operations can be performed on that data.
  • In C++, a class can contain variables, functions, constructors, destructors, static members, constants, and access specifiers.
  • The most common use is to keep related data and behavior together in one named type.
  • An object is a real variable created from a class.

Object Lifetime Boundary

  • Uninitialized members

    Initialize every data member in the constructor initializer list. Default initialization can leave fundamental types indeterminate and produce behavior that changes between builds.

C++ Classes and Objects Questions Learners Ask

A class is a user-defined type that groups data members and member functions into one blueprint.

An object is an instance of a class. It stores actual values and can call public member functions.

C++ makes class members private by default to support data hiding and safer object design.

Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.