C++ / Object-Oriented Programming in C++

Introduction to OOP in C++

This tutorial will introduce you to the basic principles of Object-Oriented Programming (OOP) in C++. You'll learn about the four main concepts of OOP and how they're used in C++.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers OOP principles such as classes, objects, inheritance, and polymorphism.

Introduction

This tutorial aims to introduce you to the fundamental principles of Object-Oriented Programming (OOP) in C++. OOP is a design philosophy that uses "objects" to develop software. The core ideas of OOP are encapsulation, inheritance, polymorphism, and abstraction.

By the end of this tutorial, you will have a clear understanding of these four principles and know how to implement them in C++.

Prerequisites:
- Basic understanding of C++
- Familiarity with the concepts of variables, functions, arrays, and pointers in C++

Step-by-Step Guide

Encapsulation

Encapsulation refers to binding the data (variables) and the methods (functions) together within an object (class). This helps maintain integrity of the data by hiding it from the outside world.

class Car {
  private:    // data members are private
    int speed;
    string color;
  public:     // methods are public
    void setSpeed(int s) { speed = s; }
    int getSpeed() { return speed; }
};

Inheritance

Inheritance is a process by which one class can acquire the properties (methods and fields) of another. With the use of inheritance, information is made manageable in a hierarchical order.

class Vehicle {   // base class
  public:
    void generalInfo() { cout << "General vehicle information." << endl; }
};

class Car: public Vehicle {   // derived class
};

Polymorphism

Polymorphism allows one interface to be used for a general class of actions. It provides a means to manage and implement different types of objects (that have a common supertype) in a uniform manner.

class Vehicle {   // base class
  public:
    virtual void generalInfo() { cout << "General vehicle information." << endl; }
};

class Car: public Vehicle {   // derived class
  public:
    void generalInfo() override { cout << "Car info." << endl; }
};

Abstraction

Abstraction simplifies complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.

class Vehicle {   // base class
  public:
    virtual void generalInfo() = 0;  // pure virtual function
};

Code Examples

Let's look at a series of examples that implement OOP principles in C++.

  1. Encapsulation
// Class definition
class Circle {
  private:
    double radius;  // Private attribute

  public:
    // Setter
    void setRadius(double r) {
      radius = r;
    }

    // Getter
    double getRadius() {
      return radius;
    }

    double getArea() {
      return 3.14 * radius * radius;
    }
};

int main() {
  Circle c1;     // Create an object of Circle
  c1.setRadius(5.0);  // Call the method with an argument
  cout << "Radius is: " << c1.getRadius() << "\n";
  cout << "Area is: " << c1.getArea();
  return 0;
}

Expected output:

Radius is: 5
Area is: 78.5
  1. Inheritance
// Base class
class Vehicle {
  public:
    string brand = "Ford";

    void honk() {
      cout << "Tuut, tuut! \n";
    }
};

// Derived class
class Car: public Vehicle {
  public:
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model;
  return 0;
}

Expected output:

Tuut, tuut! 
Ford Mustang

Summary

In this tutorial, you have learned about the four main concepts of OOP in C++: encapsulation, inheritance, polymorphism, and abstraction. Understanding these ideas is crucial for developing complex C++ applications.

Practice Exercises

  1. Exercise 1: Create a class 'Rectangle' with two private integer members 'length' and 'breadth'. Create public member functions to set and get the values of both.

  2. Exercise 2: Create a base class 'Shape' with a function 'shapeName'. Derive two classes 'Circle' and 'Square' from Shape, both having a function 'shapeName' which overrides the function in the base class.

  3. Exercise 3: Implement polymorphism by creating a base class 'Animal' with a function 'sound'. Derive classes 'Dog' and 'Cat' from Animal, both having a function 'sound' which overrides the function in the base class.

Solutions

  1. Solution 1:
class Rectangle {
  private:
    int length;
    int breadth;

  public:
    void setLength(int len) {
      length = len;
    }

    void setBreadth(int b) {
      breadth = b;
    }

    int getLength() {
      return length;
    }

    int getBreadth() {
      return breadth;
    }
};
  1. Solution 2:
class Shape {
  public:
    virtual void shapeName() { cout << "This is a general shape." << endl; }
};

class Circle: public Shape {
  public:
    void shapeName() override { cout << "This is a circle." << endl; }
};

class Square: public Shape {
  public:
    void shapeName() override { cout << "This is a square." << endl; }
};
  1. Solution 3:
class Animal {
  public:
    virtual void sound() { cout << "This is a generic animal sound." << endl; }
};

class Dog: public Animal {
  public:
    void sound() override { cout << "Woof Woof!" << endl; }
};

class Cat: public Animal {
  public:
    void sound() override { cout << "Meow Meow!" << endl; }
};

Keep practicing and experimenting with these concepts to improve your understanding. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help