Encapsulation and Abstraction in C++ and Python
0.0|0 ratingsLog in to rate
Understand access specifiers, name mangling, abstract base classes, and interfaces with parallel C++ and Python guides.
#oop#encapsulation#abstraction#cpp#python
Encapsulation and Interfaces
Encapsulation is the practice of bundling data fields and methods that manipulate them within a class, hiding internal details from outsiders.
Abstraction focuses on hiding implementation complexity and showing only essential functionality. This is achieved via abstract classes or interfaces (pure virtual classes in C++ or the abc module in Python).
C++ Abstract Shape & Encapsulation
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
// Abstract Class (Interface)
class Shape {
public:
virtual double getArea() = 0; // Pure virtual function
virtual ~Shape() = default;
};
class Circle : public Shape {
private:
double radius; // Encapsulated variable
public:
Circle(double r) : radius(r) {}
double getArea() override {
return 3.14159 * radius * radius;
}
};Python Abstract Shape & Encapsulation
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from abc import ABC, abstractmethod
class Shape(ABC): # Abstract Base Class
@abstractmethod
def get_area(self) -> float:
pass
class Circle(Shape):
def __init__(self, radius: float):
self.__radius = radius # Private member using name mangling (___radius)
def get_area(self) -> float:
return 3.14159 * self.__radius * self.__radius
# Getter property
@property
def radius(self):
return self.__radiusDiscussion
Loading discussion...