CS Engineering Gyan

Object Oriented Programming in C++

Up until now, most of the programs we have written have followed a fairly straightforward path: data is stored in variables and arrays, and functions operate on that data step by step from top to bottom. This approach, known as procedural programming, works well for small programs, but as software grows larger and more complex, keeping data and the functions that operate on it completely separate starts to create problems that are hard to manage.

Object Oriented Programming, usually shortened to OOP, is a different way of organizing code. Instead of treating data and functions as separate pieces, OOP bundles them together into a single unit called an object. Each object represents a real-world entity or concept, carrying its own data along with the functions needed to work with that data. C++ was one of the earliest widely used languages to bring this style of programming to the C family, and it remains one of the best languages to learn OOP with, since its implementation of these ideas is explicit and easy to trace.

In this tutorial, you will get a conceptual introduction to what Object Oriented Programming actually means, why it exists, and a first look at the four pillars that make it up: encapsulation, abstraction, inheritance, and polymorphism. Each of these pillars will be explored in far more depth in the chapters that follow this one.


Why Object Oriented Programming Exists

Imagine building software to manage a YouTube channel's data, tracking things like subscriber counts, video views, and upload schedules. In a purely procedural style, you might end up with several separate arrays and a long list of functions that all need to be called in the right order with the right arguments. As the number of features grows, keeping track of which function is meant to work with which piece of data becomes increasingly error-prone.

Object Oriented Programming addresses this by grouping related data and behavior into a single structure. Instead of separately managing a subscriber count variable and a set of loosely related functions, you create a single object that knows its own subscriber count and knows how to update itself. This grouping mirrors how we naturally think about real-world things, which makes the resulting code easier to understand, extend, and maintain over time.

Example

#include <iostream>

using namespace std;

class Channel {

    public:

        string name;

        int subscribers;

        void showInfo() {

            cout << name << " has " << subscribers << " subscribers" << endl;

        }

};

int main() {

    Channel csEngineeringGyan;

    csEngineeringGyan.name = "CS Engineering Gyan";

    csEngineeringGyan.subscribers = 50000;

    csEngineeringGyan.showInfo();

    return 0;

}

Output

CS Engineering Gyan has 50000 subscribers

Here, the data (name and subscribers) and the behavior (showInfo) are bundled together inside a single structure called Channel. This is the essence of Object Oriented Programming, and the rest of this tutorial builds on exactly this idea.


Class and Object: The Foundation of OOP

A class is essentially a blueprint or template that defines what data and behavior a certain kind of object will have, without actually creating anything by itself. An object, on the other hand, is a real instance created from that blueprint, with its own actual values stored in memory.

Example

#include <iostream>

using namespace std;

class Video {

    public:

        string title;

        int views;

};

int main() {

    string channel = "CS Engineering Gyan";

    Video oopIntro;

    oopIntro.title = "Introduction to OOP";

    oopIntro.views = 3200;

    cout << channel << " video title: " << oopIntro.title << endl;

    cout << channel << " video views: " << oopIntro.views << endl;

    return 0;

}

Output

CS Engineering Gyan video title: Introduction to OOP

CS Engineering Gyan video views: 3200

Here, Video is the class, describing what any video will generally look like, while oopIntro is an object, an actual video with real values filled in. Many different objects can be created from the same class, each holding its own separate set of values.


The Four Pillars of OOP

Object Oriented Programming is generally described using four core ideas that work together. While each one will be covered in a full, dedicated chapter later, it helps to understand the basic idea behind each pillar before diving deeper.

1. Encapsulation

Encapsulation refers to bundling data and the functions that operate on that data into a single unit, while also controlling how that data can be accessed from outside the object. This protects the internal details of an object and prevents external code from directly modifying its data in unintended ways.

Example

#include <iostream>

using namespace std;

class Playlist {

    private:

        int videoCount;

    public:

        void addVideo() {

            videoCount++;

        }

        int getVideoCount() {

            return videoCount;

        }

};

int main() {

    string channel = "CS Engineering Gyan";

    Playlist dsaPlaylist;

    dsaPlaylist.addVideo();

    dsaPlaylist.addVideo();

    dsaPlaylist.addVideo();

    cout << channel << " DSA playlist video count: " << dsaPlaylist.getVideoCount() << endl;

    return 0;

}

Output

CS Engineering Gyan DSA playlist video count: 3

Notice that videoCount is marked private, meaning it cannot be accessed or changed directly from outside the class. Instead, controlled functions like addVideo() and getVideoCount() are used, which is the core idea behind encapsulation.

2. Abstraction

Abstraction means hiding the complicated internal details of how something works, and exposing only the essential features that a user of the object actually needs. It focuses on what an object does rather than how it does it internally.

Example

#include <iostream>

using namespace std;

class VideoUploader {

    public:

        void uploadVideo(string title) {

            cout << "Processing upload for: " << title << endl;

            cout << "Video published successfully" << endl;

        }

};

int main() {

    string channel = "CS Engineering Gyan";

    VideoUploader uploader;

    cout << channel << " uploading new video" << endl;

    uploader.uploadVideo("Pointers in C++");

    return 0;

}

Output

CS Engineering Gyan uploading new video

Processing upload for: Pointers in C++

Video published successfully

The person calling uploadVideo() does not need to know how the encoding, storage, or publishing actually happens internally. All the complexity is hidden away, and only a simple, easy-to-use function is exposed, which is exactly what abstraction is about.

3. Inheritance

Inheritance allows one class to acquire the properties and behavior of another existing class. This makes it possible to reuse code from a general class while adding or customizing features in a more specific class, rather than writing everything again from scratch.

Example

#include <iostream>

using namespace std;

class Content {

    public:

        string channel = "CS Engineering Gyan";

        void showChannel() {

            cout << "Content published by: " << channel << endl;

        }

};

class ShortVideo : public Content {

    public:

        int durationSeconds = 45;

};

int main() {

    ShortVideo reel;

    reel.showChannel();

    cout << "Short video duration: " << reel.durationSeconds << " seconds" << endl;

    return 0;

}

Output

Content published by: CS Engineering Gyan

Short video duration: 45 seconds

Here, ShortVideo inherits the channel property and the showChannel function from Content, without needing to redefine them. It simply adds its own extra property, durationSeconds, on top of what it already inherited.

4. Polymorphism

Polymorphism means "many forms," and it refers to the ability of a function or operation to behave differently depending on the context in which it is used. In C++, this often shows up as the same function name performing different tasks depending on the arguments passed to it.

Example

#include <iostream>

using namespace std;

class Stats {

    public:

        void show(int views) {

            cout << "Video views: " << views << endl;

        }

        void show(string comment) {

            cout << "Latest comment: " << comment << endl;

        }

};

int main() {

    string channel = "CS Engineering Gyan";

    Stats channelStats;

    cout << channel << " stats update:" << endl;

    channelStats.show(4500);

    channelStats.show("Great explanation, thanks!");

    return 0;

}

Output

CS Engineering Gyan stats update:

Video views: 4500

Latest comment: Great explanation, thanks!

Both functions share the same name, show, but the compiler decides which version to run based on the type of argument passed. This is a simple example of compile-time polymorphism, one of the two forms of polymorphism supported in C++.


Procedural Programming vs Object Oriented Programming

While both approaches can be used to solve the same problems, they organize a program's structure in fundamentally different ways. Understanding this difference makes it much easier to appreciate why OOP is preferred for larger, more complex software systems.

Procedural Programming Object Oriented Programming
Data and functions are kept as separate entities. Data and functions are bundled together inside objects.
Focus is on writing a sequence of steps to perform a task. Focus is on creating objects that represent real-world entities.
Reusing code across programs is comparatively harder. Inheritance allows classes to reuse and extend existing code.
Data can usually be accessed and modified from anywhere. Encapsulation restricts and controls access to internal data.

Real-World Analogy for OOP

A helpful way to understand OOP is to think of a class as the design blueprint for a car, describing features like color, speed, and fuel level, along with actions like accelerating or braking. The actual cars built from that blueprint are the objects, each with their own specific color and current speed, yet all behaving according to the same underlying design.

Encapsulation is similar to how a driver does not need to understand the internal wiring of the engine to drive the car, since the dashboard and pedals expose only what is needed. Abstraction is why the driver only sees a simple accelerator pedal rather than the complex combustion process happening underneath. Inheritance is like a sports car model being built on top of a standard car design, reusing most of its features while adding extra ones. Polymorphism is similar to how pressing the same brake pedal produces a gentle stop on a highway but a sharp stop in an emergency, the same action producing different results depending on the situation.


Advantages and Limitations of OOP

Advantages Limitations
Groups related data and behavior together, improving code organization. Can introduce extra complexity for very small, simple programs.
Encourages code reuse through inheritance, reducing duplication. Poorly designed class hierarchies can become difficult to maintain.
Encapsulation improves security by restricting direct data access. Object-oriented programs can sometimes run slightly slower than tightly written procedural code.

Best Practices While Learning OOP


Common Mistakes Beginners Make

Mistake Correct Practice
Confusing a class with an object. Remember that a class is a blueprint, while an object is an actual instance built from it.
Making all class members public without a clear reason. Keep internal data private unless there is a specific need to expose it directly.
Using inheritance just to avoid retyping unrelated code. Use inheritance only when one class is genuinely a specialized version of another.
Assuming OOP is only about writing classes, without understanding the underlying design ideas. Focus on encapsulation, abstraction, inheritance, and polymorphism as design principles, not just syntax.

Frequently Asked Interview Questions

  1. What is Object Oriented Programming?
    Object Oriented Programming is a programming style that organizes code around objects, which bundle data and the functions that operate on that data together.
  2. What is the difference between a class and an object?
    A class is a blueprint that defines data and behavior, while an object is an actual instance created from that blueprint with real values.
  3. What are the four main pillars of OOP?
    The four main pillars are encapsulation, abstraction, inheritance, and polymorphism.
  4. What is encapsulation in simple terms?
    Encapsulation is bundling data and related functions together while restricting direct outside access to that data.
  5. What is abstraction in simple terms?
    Abstraction is hiding complex internal implementation details and exposing only the necessary features to the user.
  6. Why is inheritance useful in OOP?
    Inheritance allows a new class to reuse the properties and behavior of an existing class, reducing duplicate code.
  7. What is polymorphism in OOP?
    Polymorphism is the ability of a function or operation to behave differently depending on the context or type of data involved.
  8. How is OOP different from procedural programming?
    Procedural programming separates data and functions, while OOP bundles them together inside objects that model real-world entities.

Summary

Object Oriented Programming shifts the focus from writing a long sequence of instructions to designing objects that represent real entities, each carrying its own data and behavior. This section introduced the core motivation behind OOP, the relationship between classes and objects, and a first look at the four foundational pillars: encapsulation, abstraction, inheritance, and polymorphism.

While each of these pillars was only briefly introduced here, they form the backbone of everything that follows in object-oriented C++ programming. A solid conceptual understanding at this stage makes it significantly easier to follow the deeper, more detailed explanations of classes, objects, inheritance, and polymorphism in the upcoming chapters.

With this foundation in place, you are now ready to explore classes and objects in much greater depth, including constructors, member functions, and access specifiers, which form the practical building blocks of every object-oriented C++ program.


← Previous: Pointers in C++ Next: Classes and Objects →

Home Visit Our YouTube Channel