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

Implementing Encapsulation and Abstraction

In this tutorial, you'll learn how to implement Encapsulation and Abstraction in C++. These concepts are key to writing secure and efficient code.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

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

1. Introduction

Tutorial's Goal

This tutorial aims to guide you through the implementation of two fundamental Object-Oriented Programming (OOP) principles, Encapsulation, and Abstraction, in C++.

Learning Outcomes

By the end of this tutorial, you will:

  • Understand the concepts of Encapsulation and Abstraction.
  • Know how to implement Encapsulation and Abstraction in C++.
  • Be able to apply these principles to write secure, efficient, and maintainable code.

Prerequisites

To get the most out of this tutorial, you should have a basic understanding of:

  • C++ syntax and programming basics
  • The concept of classes and objects in C++

2. Step-by-Step Guide

Encapsulation

Encapsulation is one of the four fundamentals of OOP. It refers to the bundling of data (variables) and methods (functions) into a single unit called a class. In C++, we achieve encapsulation through 'classes'.

A key feature of encapsulation is data hiding - the class's data can only be accessed through the methods of that class.

class EncapsulationExample {
    private:
        int x;  // private data can only be accessed by methods within the class

    public:
        void setX(int a) {  // method to set the value of x
            x = a;
        }

        int getX() {  // method to get the value of x
            return x;
        }
};

Abstraction

Abstraction, another fundamental concept in OOP, is about hiding the complex details and showing only the essentials. In C++, we achieve this through 'abstract classes' and 'interfaces'.

class AbstractExample {
    public:
        virtual void function1() = 0;  // pure virtual function makes this class Abstract
};

class ImplementAbstract : public AbstractExample {
    public:
        void function1() {  // implementation of the abstract function
            //...
        }
};

3. Code Examples

Example of Encapsulation

This example shows how to encapsulate data and methods within a class.

class Car {
    private:
        int speed;

    public:
        void setSpeed(int s) {
            if(s < 0) {
                cout << "Speed cannot be negative." << endl;
                return;
            }
            speed = s;
        }

        int getSpeed() {
            return speed;
        }
};

int main() {
    Car car;
    car.setSpeed(50);
    cout << "The car is travelling at " << car.getSpeed() << " km/h." << endl;
    return 0;
}

In this example, the speed variable is encapsulated in the Car class. It can only be accessed and modified through the setSpeed and getSpeed methods.

Example of Abstraction

This example shows how to use abstract classes in C++.

class AbstractClass {
    public:
        virtual void doSomething() = 0;  // Pure virtual function
};

class ConcreteClass : public AbstractClass {
    public:
        void doSomething() {
            cout << "Doing something!" << endl;
        }
};

int main() {
    ConcreteClass cc;
    cc.doSomething();  // Prints "Doing something!"
    return 0;
}

In this example, AbstractClass is an abstract class with a pure virtual function. ConcreteClass is a derived class that implements the pure virtual function.

4. Summary

This tutorial has covered:

  • The concepts of Encapsulation and Abstraction in C++.
  • How to implement Encapsulation and Abstraction in C++ using classes, methods, and interfaces.
  • Examples of encapsulated and abstract classes in C++.

To further your understanding, you can implement more classes using these concepts. You can also explore the other two principles of OOP - Inheritance and Polymorphism.

5. Practice Exercises

  1. Create a Person class with encapsulated name and age variables. Provide methods to set and get these variables.
  2. Create an abstract Shape class with a pure virtual calculateArea method. Then create Rectangle and Circle classes that implement this method.

Solutions

  1. Encapsulated Person class
class Person {
    private:
        string name;
        int age;

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

        void setAge(int a) {
            if(a < 0) {
                cout << "Age cannot be negative." << endl;
                return;
            }
            age = a;
        }

        string getName() {
            return name;
        }

        int getAge() {
            return age;
        }
};
  1. Abstract Shape class and its implementations
class Shape {
    public:
        virtual double calculateArea() = 0;
};

class Rectangle : public Shape {
    private:
        double width, height;

    public:
        Rectangle(double w, double h) : width(w), height(h) {}

        double calculateArea() {
            return width * height;
        }
};

class Circle : public Shape {
    private:
        double radius;

    public:
        Circle(double r) : radius(r) {}

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

These exercises help you understand encapsulation and abstraction better. Try creating more examples for more practice. 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

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

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