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.
Section overview
5 resourcesCovers 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
- Create a
Personclass with encapsulatednameandagevariables. Provide methods to set and get these variables. - Create an abstract
Shapeclass with a pure virtualcalculateAreamethod. Then createRectangleandCircleclasses that implement this method.
Solutions
- Encapsulated
Personclass
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;
}
};
- Abstract
Shapeclass 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article