Object-Oriented Programming in C++ Demystified

Are you new to programming and wondering what Object-Oriented Programming (OOP) is all about? Look no further! In this post, we will demystify the world of OOPs in C++. We will cover the fundamentals of this interesting programming paradigm, including the concepts of objects and classes. By the end of this post, you’ll have a solid understanding of OOPs and be ready to start creating your own programs using C++. So, let’s get started!

Object-oriented programming (OOP) is a programming paradigm that uses objects to represent and manipulate data. OOP is a popular programming paradigm and is widely used in software development. C++ is one of the most widely used programming languages that supports object-oriented programming. In this article, we will discuss object-oriented programming in C++ in detail.

Object Oriented Programming Classes and Objects C++

Objects

In programming, an object is a self-contained unit that represents a real-world entity or concept. Objects contain both data (properties) and code (methods) that operate on that data. They are the fundamental building blocks of object-oriented programming and provide a way to model complex systems. Objects enable you to organize code in a modular way, making it easier to manage and reuse.

Think of an object as a container that holds a set of attributes and behaviors. For example, a car can be represented as an object with attributes such as color, make, model, and year, and behaviors such as accelerating, braking, and turning.

Classes

A class is a blueprint for creating objects. It defines a set of attributes and methods that an object of that class will have. The attributes are the data members of the class, and the methods are the member functions of the class. The objects are instances of the class, and they are created from the class blueprint.

In C++, the keyword ‘class’ is used to define a class. The class definition consists of the class name, data members, and member functions. For example, let’s define a class named ‘Person’ that has two data members, ‘name’ and ‘age’:

				
					class Person {
    private:
        string name;
        int age;

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

        void setAge(int a) {
            age = a;
        }

        string getName() {
            return name;
        }

        int getAge() {
            return age;
        }
};

				
			

In the above example, the ‘Person’ class has two data members, ‘name’ and ‘age’, and four member functions, ‘setName’, ‘setAge’, ‘getName’, and ‘getAge’. The ‘setName’ and ‘setAge’ functions are used to set the name and age of the person, and the ‘getName’ and ‘getAge’ functions are used to get the name and age of the person.

To create an object of the ‘Person’ class, we can use the following code:

				
					```(C++)
Person p;
```

				
			

To get the name and age of the person, we can use the ‘getName’ and ‘getAge’ functions as follows.

				
					```(C++)
string name = p.getName();
int age = p.getAge();
```

				
			

Object-Oriented Programming offers some great features that make it very useful. Some of the extremely significant features of Object Oriented Programming are:

  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

Inheritance

Inheritance is a mechanism in which one class inherits the properties of another class. The class that inherits the properties is called the derived class or the subclass, and the class from which it inherits the properties is called the base class or the superclass.

In C++, the keyword ‘public’ is used to inherit the properties of a base class. For example, let’s define a class named ‘Student’ that inherits from the ‘Person’ class

				
					```(C++)
class Student: public Person {
    private:
        int rollNumber;

    public:
        void setRollNumber(int r) {
            rollNumber = r;
        }

        int getRollNumber() {
            return rollNumber;
        }
};

				
			

In the above example, the ‘Student’ class inherits from the ‘Person’ class using the ‘public’ keyword. The ‘Student’ class has an additional data member ‘rollNumber’ and two member functions ‘setRollNumber’ and ‘getRollNumber’.

To create an object of the ‘Student’ class, we can use the following code:

				
					```(C++)
Student s;
```

				
			

This creates an object of the ‘Student’ class named ‘s’. To set the name, age, and roll number of the student, we can use the ‘setName’, ‘setAge’, and ‘setRollNumber’ functions as follows:

				
					s.setName(“Mary”);
s.setAge(20);
s.setRollNumber(101);



				
			

To get the name, age, and roll number of the student, we can use the ‘getName’, ‘getAge’, and ‘getRollNumber’ functions as follows:

				
					string name = s.getName();
int age = s.getAge();
int rollNumber = s.getRollNumber();


				
			

Polymorphism

Polymorphism is a mechanism in which an object can take many forms. Polymorphism allows us to write code that can work with objects of different classes that are related by inheritance.

In C++, there are two types of polymorphism: compile-time polymorphism and runtime polymorphism.

Compile-time polymorphism is also known as static polymorphism, and it is achieved using function overloading and operator overloading. Function overloading allows us to define multiple functions with the same name but different parameters. The correct function to call is determined at compile time based on the arguments passed to the function. Operator overloading allows us to redefine the meaning of operators such as ‘+’ and ‘-‘ for user-defined classes.

Runtime polymorphism is also known as dynamic polymorphism, and it is achieved using virtual functions and function overriding. Virtual functions are functions that are declared in a base class and can be overridden by the derived classes. The correct function to call is determined at runtime based on the type of the object. Function overriding allows us to redefine the implementation of a virtual function in the derived class.

For example, let’s define a virtual function named ‘printDetails’ in the ‘Person’ class and override it in the ‘Student’ class:

				
					class Person {
    private:
        string name;
        int age;

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

        void setAge(int a) {
            age = a;
        }

        string getName() {
            return name;
        }

        int getAge() {
            return age;
        }

        virtual void printDetails() {
            cout << “Name: “ << name << endl;
            cout << “Age: “ << age << endl;
        }
};

class Student : public Person {
    private:
        int rollNumber;

    public:
        void setRollNumber(int r) {
            rollNumber = r;
        }

        int getRollNumber() {
            return rollNumber;
        };

        void printDetails() {
            cout << “Name: “ << getName() << endl;
            cout << “Age: “ << getAge() << endl;
            cout << “Roll Number: “ << getRollNumber() << endl;
        }
};

				
			

In the above example, the ‘Person’ class has a virtual function named ‘printDetails’ that prints the name and age of the person. The ‘Student’ class overrides the ‘printDetails’ function to print the name, age, and roll number of the student.

To call the ‘printDetails’ function on an object of the ‘Person’ class or the ‘Student’ class, we can use the following code:

				
					Person* p = new Person();
Student* s = new Student();

p->setName(“John”);
p->setAge(30);
s->setName(“Mary”);
s->setAge(20);
s->setRollNumber(101);

p->printDetails();
s->printDetails();
```


				
			

This code creates two objects, one of the ‘Person’ class and one of the ‘Student’ class, and sets their attributes. The ‘printDetails’ function is then called on both objects using a pointer to the base class ‘Person’. Since ‘printDetails’ is a virtual function, the correct implementation is called based on the type of the object.

Encapsulation

Encapsulation is a mechanism in which the data and the functions that manipulate the data are combined into a single unit called a class. Encapsulation ensures that the data is not accessible from outside the class and can only be accessed through the member functions of the class.

To demonstrate encapsulation, let’s define a class named ‘BankAccount’ that encapsulates the balance of a bank account and provides functions to deposit and withdraw money from the account:

				
					C++)
class BankAccount {
    private:
        float balance;

    public:
        BankAccount() {
            balance = 0;
        }

        void deposit(float amount) {
            balance += amount;
        }

        void withdraw(float amount) {
            if (balance >= amount) {
                balance -= amount;
            }
        }

        float getBalance() {
            return balance;
        }
};

				
			

In the above example, the ‘BankAccount’ class encapsulates the balance of a bank account and provides functions to deposit and withdraw money from the account. The ‘balance’ variable is declared as private, which means that it can only be accessed from within the class. The ‘deposit’ and ‘withdraw’ functions are declared as public, which means that they can be called from outside the class to deposit and withdraw money from the account. The ‘getBalance’ function is also declared as public, which allows us to get the balance of the account from outside the class.

To use the ‘BankAccount’ class, we can create an object of the class and call its functions as follows:

				
					C++)
class BankAccount {
    private:
        float balance;

    public:
        BankAccount() {
            balance = 0;
        }

        void deposit(float amount) {
            balance += amount;
        }

        void withdraw(float amount) {
            if (balance >= amount) {
                balance -= amount;
            }
        }

        float getBalance() {
            return balance;
        }
};

				
			

This code creates an object of the ‘BankAccount’ class, deposits 1000 into the account, prints the balance of the account, withdraws 500 from the account, and prints the balance of the account again.

Abstraction

Abstraction is the process of simplifying complex real-world problems into simpler, more manageable components that can be easily understood and implemented in code. In object-oriented programming, abstraction is achieved by defining abstract classes and interfaces that define the properties and behaviors of objects without specifying their implementation.

Let’s take an example to understand the concept of abstraction in C++. Consider a shape class that represents different types of shapes such as rectangles, circles, and triangles. We can define an abstract class named ‘Shape’ that defines the common properties and behaviors of all shapes, without specifying the implementation details. Here’s how we can define the ‘Shape’ class in C++:

				
					```(C++)
class Shape;
    public:
        virtual float area() = 0;
        virtual float perimeter() = 0;
};

				
			

In the above example, the ‘Shape’ class is defined as an abstract class using the ‘virtual’ keyword. The class has two pure virtual functions, ‘area’ and ‘perimeter’, which define the properties of all shapes without specifying their implementation. Since these functions are pure virtual, they do not have any implementation and must be implemented by the derived classes that inherit from the ‘Shape’ class.

Now, let’s define some concrete classes that inherit from the ‘Shape’ class and provide their own implementation of the ‘area’ and ‘perimeter’ functions. For example, here’s how we can define a rectangle class that inherits from the ‘Shape’ class:

				
					C++)
class Rectangle : public Shape {
    private:
        float length;
        float width;

    public:
        Rectangle(float l, float w) {
            length = 1;
            width = w;
        }

        float area() {
            return length * width;
        }

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

				
			

In the above example, the ‘Rectangle’ class inherits from the ‘Shape’ class and provides its own implementation of the ‘area’ and ‘perimeter’ functions. The class has two private variables, ‘length’ and ‘width’, which define the dimensions of the rectangle. The ‘area’ and ‘perimeter’ functions are implemented using the length and width variables to calculate the area and perimeter of the rectangle.

Similarly, we can define other concrete classes such as the ‘Circle’ and ‘Triangle’ classes that inherit from the ‘Shape’ class and provide their own implementation of the ‘area’ and ‘perimeter’ functions.

By using abstraction, we can define a common interface for all shapes and provide a way to calculate their properties without worrying about their implementation details. This makes it easier to create and manage complex systems that involve multiple types of shapes.

Additional Tips:

Here are a few additional tips to keep in mind when using object-oriented programming in C++:

  1. Design your classes carefully: The design of your classes will have a significant impact on the structure and behavior of your software system. Therefore, it’s important to carefully consider the responsibilities and properties of each class and how they will interact with other classes in the system.
  2. Use access specifiers wisely: Access specifiers can help you control the visibility of your class properties and methods, but they can also introduce unnecessary complexity and make your code harder to maintain. Use them sparingly and only when necessary.
  3. Follow naming conventions: Following naming conventions for classes, properties, and methods can make your code more readable and easier to understand. Use descriptive names that accurately reflect the purpose and functionality of each class, property, and method.
  4. Avoid global variables: Global variables can introduce unnecessary complexity and make it harder to understand and debug your code. Instead, use local variables and pass them as parameters to functions and methods.
  5. Keep your code modular: Object-oriented programming allows you to break down complex systems into smaller, more manageable parts. Try to keep your classes and functions as modular as possible, so that they can be easily reused and modified.
Object-Oriented Programming in C++

Conclusion

In conclusion, object-oriented programming is a powerful paradigm that enables the creation of complex software systems. C++ provides robust support for object-oriented programming concepts such as classes, objects, inheritance, and polymorphism. By mastering these concepts, you can develop software systems that are more modular, scalable, and maintainable. Object-oriented programming is a valuable skill for any programmer to have, and with practice and experience, you can become proficient in it and use it to solve a wide range of programming problems.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top