C++ Object-Oriented Programming, CSE – Study Notes
offline

Difficulty: Intermediate | Prerequisites: C++ variables, data types, functions, pass by value/reference.

TL;DR

Object-oriented programming in C++ organises code around classes (blueprints) and objects (instances of those blueprints), bundling data and the functions that operate on it into a single unit. Access specifiers (private, public, protected) control what outside code can see and change, while constructors and destructors handle setup and cleanup automatically. Once you grasp encapsulation, accessor/mutator patterns, and how objects are passed to functions, you have the foundation for everything else in OOP.

Key Terms

Object-oriented programming (OOP)

A programming paradigm that structures code around objects, which encapsulate data and the functions (methods) that operate on that data. The three pillars are encapsulation, inheritance, and polymorphism.

In simple terms, this means: instead of a loose collection of functions and variables, you group related data and behaviour together into self-contained units.

Encapsulation

The principle of bundling data (member variables) and functions (member functions) into a single class, and restricting direct access to some of those members.

Think of it as: a protective wrapper. The internal details are hidden; the outside world interacts only through the public interface.

Class

A user-defined type that serves as a blueprint for creating objects. It specifies the data members and member functions that objects of that type will have.

Think of it as: a cookie cutter. The class defines the shape; each cookie (object) is stamped from it.

Object / instance

A concrete variable created from a class. Each object has its own copy of the class's data members.

In simple terms, this means: if the class is the blueprint, the object is the finished house.

Abstract data type (ADT)

A data type defined by what operations it supports, with its implementation details hidden from the user. In C++, classes are the standard way to implement ADTs.

Think of it as: you know what buttons to press but you do not need to see the wiring inside.

Access specifier

A keyword that controls the visibility of class members: private (hidden from outside), public (accessible from outside), or protected (accessible in derived classes).

In simple terms, this means: access specifiers decide who is allowed to read or change each piece of the class.

Member variable / attribute

A variable declared inside a class that stores data belonging to each object.

Think of it as: the properties of the object. A Circle's radius is a member variable.

Member function / method

A function declared inside a class that defines behaviour for objects of that class.

Think of it as: the actions an object can perform. A Circle's getArea() is a member function.

Constructor

A special public member function with the same name as the class. It is called automatically when an object is created and is used to initialise data members.

In simple terms, this means: the setup routine that runs the moment an object is born.

Default constructor

A constructor that takes no parameters. If you do not write any constructor, the compiler generates one, but it does not initialise your data members to meaningful values.

Think of it as: the no-argument version. It creates the object with whatever default state you have defined (or garbage values if you have not).

Destructor

A special member function named with a tilde (~) prefix followed by the class name. Called automatically when an object is destroyed. Used to release resources.

Think of it as: the cleanup crew that runs when the object goes out of scope.

Inline member function

A member function defined inside the class declaration (rather than separately). The compiler may embed its code directly at each call site for efficiency.

In simple terms, this means: a short function written right in the class body, hinting to the compiler to skip the overhead of a normal function call.

Accessor (getter)

A member function that returns the value of a private data member without modifying it. Typically marked const.

Think of it as: a read-only window into private data.

Mutator (setter)

A member function that modifies a private data member, often with validation.

Think of it as: a controlled door for changing private data.

Struct (structure)

Similar to a class, but members default to public access. Commonly used for simple data groupings with no complex behaviour.

In simple terms, this means: a lightweight class where everything is accessible by default.

Enum (enumeration)

A user-defined type consisting of a set of named integral constants (e.g. Spring = 0, Summer = 1, Fall = 2, Winter = 3).

Think of it as: a way to give meaningful names to a fixed set of values instead of using raw integers.

Constant reference (const Type&)

A reference parameter marked const, allowing the function to access the original object without copying it, while guaranteeing it will not be modified.

Think of it as: "look but do not touch." Efficient and safe.

Core Content

OOP Principles

  • OOP centres on objects that bundle data and functions together

  • The three core principles are encapsulation (hiding internal details), inheritance (building new classes from existing ones), and polymorphism (using a single interface for different underlying types)

  • OOP supports modular, reusable code and models real-world entities naturally

Abstract Data Types (ADTs)

  • An ADT defines what operations are available, without exposing how they are implemented

  • In C++, classes are the mechanism for creating ADTs

  • The user of a class interacts with it through its public interface; the private implementation can change without affecting calling code

Class Declaration and Objects

  • A class declaration defines the blueprint: data members and member functions

  • An object is created by declaring a variable of the class type

  • The class declaration ends with a semicolon after the closing brace

  • Example:

class Circle {
    // members
};

Circle myCircle; // creates an object

Encapsulation and Access Specifiers

  • private: members are accessible only within the class itself. Data members should almost always be private.

  • public: members are accessible from any code that has an object of the class. Member functions that form the class's interface are typically public.

  • protected: members are accessible within the class and its derived (child) classes. Relevant when inheritance is introduced.

  • In a class, the default access specifier is private. In a struct, the default is public.

Member Variables and Member Functions

  • Member variables (attributes) store each object's data

  • Member functions (methods) define the object's behaviour

  • Both are accessed via the dot operator on an object: myCircle.getRadius()

Constructor Functions

  • Constructors share the class name and have no return type

  • Called automatically when an object is created

  • Used to initialise data members to known, valid states

  • Default constructor: takes no parameters. If you write no constructors at all, the compiler generates one, but it does not initialise your members to anything useful.

  • Constructors can be overloaded to accept different sets of initial values

  • Example:

class Rectangle {
public:
    Rectangle() { width = height = 0; }              // default
    Rectangle(double w, double h) { width = w; height = h; } // parameterised
private:
    double width, height;
};

Destructor Functions

  • Named with a tilde prefix: ~ClassName()

  • Called automatically when an object goes out of scope or is deleted

  • Takes no parameters and cannot be overloaded

  • Used to release dynamically allocated memory, close files, or perform other cleanup

Inline Member Functions

  • A member function defined inside the class body is implicitly inline

  • The compiler may replace calls with the function's body directly, avoiding call overhead

  • Best suited for very short functions (one or two lines)

  • Example:

class Square {
public:
    void setSide(double s) { side = s; } // inline
private:
    double side;
};

Accessor and Mutator Functions

  • Accessors (getters) return a private member's value without modifying the object. They should be marked const.

  • Mutators (setters) change a private member's value, often including validation logic.

  • This pattern enforces controlled access to private data.

  • Examples:

double getRadius() const { return radius; } // accessor
void setRadius(double r) { radius = r; }    // mutator

Creating and Using Class Objects

  • Objects are created like any other variable: Circle myCircle;

  • Member functions are called through the dot operator: myCircle.setRadius(5.0);

  • Each object maintains its own independent copy of the class's data members

Structured Types and Enumerations

  • Structs are similar to classes but default to public access. Commonly used for simple data groupings (e.g. a point with x and y coordinates).

  • Enums define a set of named integral constants, making code more readable than raw integers.

  • Example:

enum Season {Spring, Summer, Fall, Winter};
Season favoriteSeason = Summer;
cout << favoriteSeason; // outputs 1 (Spring=0, Summer=1)

Passing Objects by Constant Reference

  • Passing a large object by value copies the entire object, which is expensive

  • Passing by const reference (const Type&) avoids the copy and prevents the function from modifying the object

  • Example:

void display(const MyClass& obj) {
    // can read obj but cannot modify it
}
  • Combines efficiency (no copy overhead) with safety (no accidental changes)

Common Misconceptions

  • Students often forget the semicolon after the closing brace of a class declaration. This is a syntax error the compiler will flag, but the error message can be confusing because it often points to the next line of code rather than the missing semicolon.

  • Students often think constructors have a return type. They do not. Writing void Rectangle() makes it an ordinary member function, not a constructor.

  • Students often assume that declaring a class also creates an object. It does not. The class is the blueprint; you must declare a variable of that class type to create an object.

  • Students often access private members directly from outside the class (e.g. myCircle.radius = 5;). Private members require accessor and mutator functions.

Why It Matters / Exam Flags

  • ⚠️ Know the three access specifiers and the default for class (private) vs struct (public). This is a common multiple-choice question.

  • ⚠️ Constructor questions are heavily tested: when is a constructor called, what happens if you do not provide one, and how constructor overloading works.

  • ⚠️ Be able to write a complete class from scratch: private data, public constructor, accessors, mutators, and a member function that uses the data.

  • ⚠️ Understand const member functions: an accessor should be marked const, and a const object can only call const member functions.

  • ⚠️ Passing objects by const reference vs by value: know the efficiency and safety trade-offs.

Quick Self-Test

  1. True or False: In a class declaration, members are private by default.

  1. Fill in the blank: A constructor has the same name as the ______ and no return type.

  1. True or False: A destructor can be overloaded to accept different parameters.

  1. Fill in the blank: A member function that retrieves a private data member without changing it is called an ______.

  1. True or False: A struct's members are private by default.

Answers: 1. True. 2. Class. 3. False (destructors take no parameters and cannot be overloaded). 4. Accessor (or getter). 5. False (they are public by default).

Practice Q&A

Q: What is the difference between a class and an object?

A: A class is a blueprint that defines data members and member functions. An object is a specific instance of a class, with its own copy of the data members.

Q: Write a simple class called Counter with a private integer count, a default constructor that sets count to 0, an increment() function, and a getCount() accessor.

A:

class Counter {
public:
    Counter() { count = 0; }
    void increment() { count++; }
    int getCount() const { return count; }
private:
    int count;
};

Q: Why should data members be private rather than public?

A: Private data members enforce encapsulation. Outside code must use accessor and mutator functions, which lets the class validate changes and maintain a consistent internal state. If data members are public, any code can set them to invalid values.

Q: What does the const keyword mean at the end of a member function declaration, as in int getCount() const?

A: It promises that the function will not modify any data members of the object. A const object can only call const member functions.

Q: When would you pass an object by const reference instead of by value?

A: When the object is large (copying it would be expensive) and the function does not need to modify it. Const reference gives the function read-only access to the original, avoiding both the cost of copying and the risk of accidental modification.

Connections to Other Topics

OOP builds directly on everything covered in the functions material. Member functions are functions with an implicit connection to the object's data, and the same rules about parameters, return values, overloading, and default arguments apply.

When you reach inheritance and polymorphism later in the course, the class structure and access specifiers covered here form the foundation. Protected access only becomes relevant once derived classes are introduced.

Arrays of objects and dynamically allocated objects (using new and delete) combine the array/pointer topics with the constructor and destructor patterns described here.

Related Terms / Search Tags

C++ OOP, object-oriented programming, class, object, instance, encapsulation, data hiding, information hiding, access specifier, private, public, protected, member variable, attribute, data member, member function, method, constructor, default constructor, parameterised constructor, destructor, tilde, inline function, accessor, getter, mutator, setter, const member function, abstract data type, ADT, struct, structure, enum, enumeration, const reference, pass by const reference, dot operator, scope resolution operator, class declaration, class definition, blueprint