Cheat Sheet Oops
Cheat Sheet Oops
● Class: Blueprint for creating objects. Defines attributes (data) and methods
(functions).
Syntax (C++):
class ClassName {
private:
int attribute;
public:
void method() { ... }
};
●
Syntax (Python):
class ClassName:
def __init__(self, attribute):
self.attribute = attribute
def method(self):
pass
●
1.2. Inheritance
● Definition: Mechanism to create a new class using the properties and methods of
an existing class.
Syntax (C++):
class Base {
public:
void baseMethod() { ... }
};
class Derived(Base):
def derived_method(self):
pass
●
1.3. Polymorphism
● Definition: Ability to present the same interface for different underlying forms
(data types). Includes method overloading and overriding.
class Derived(Base):
def display(self):
pass
●
1.4. Encapsulation
● Definition: Bundling data and methods that operate on the data within one unit
(e.g., a class). Protects the data from outside interference.
Syntax (C++):
class Person {
private:
int age;
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
●
Syntax (Python):
class Person:
def __init__(self, age):
self.__age = age
def get_age(self):
return self.__age
●
1.5. Abstraction
● Definition: Hiding the complex implementation details and showing only the
essential features.
class Abstract(ABC):
@abstractmethod
def pure_virtual_method(self):
pass
●
2. Common OOP Terminology
2.1. Constructor
Syntax (C++):
ClassName() { ... }
●
Syntax (Python):
def __init__(self, ...):
...
●
2.2. Destructor
Syntax (C++):
~ClassName() { ... }
●
Syntax (Python):
def __del__(self):
...
●
● Definition: Class members that are shared among all instances of the class.
Syntax (C++):
class Example {
public:
static int staticValue;
};
●
Syntax (Python):
class Example:
static_value = 0
●
● Definition: Allows one class to access private and protected members of another
class.
Syntax:
class A;
class B {
friend class A;
};
●
3. Practical Examples
3.1. Example: Class and Object
● Definition:
● Create a class Car and instantiate it.
C++ Code:
class Car {
public:
string model;
void start() { cout << "Car started"; }
};
int main() {
Car myCar;
myCar.model = "Toyota";
myCar.start();
return 0;
}
●
Python Code:
class Car:
def __init__(self, model):
self.model = model
def start(self):
print("Car started")
my_car = Car("Toyota")
my_car.start()
●
● Definition:
● Create a base class Animal and a derived class Dog.
C++ Code:
class Animal {
public:
void speak() { cout << "Animal sound"; }
};
Python Code:
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def bark(self):
print("Woof")
●
● Definition:
● Override methods in derived classes.
C++ Code:
class Base {
public:
virtual void show() { cout << "Base class"; }
};
Python Code:
class Base:
def show(self):
print("Base class")
class Derived(Base):
def show(self):
print("Derived class")
●
● Definition:
● Use getters and setters to access private data.
C++ Code:
class Person {
private:
int age;
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
●
Python Code:
class Person:
def __init__(self, age):
self.__age = age
def get_age(self):
return self.__age
●
Certainly! Here’s a continuation of the OOP cheat sheet, diving deeper into advanced
concepts and practical implementations.
● Definition: A class can inherit from more than one base class.
Syntax (C++):
class Base1 {
public:
void method1() { ... }
};
class Base2 {
public:
void method2() { ... }
};
Syntax (Python):
class Base1:
def method1(self):
pass
class Base2:
def method2(self):
pass
Syntax (C++):
class Interface {
public:
virtual void pureMethod() = 0; // Pure virtual function
};
●
Syntax (Python):
from abc import ABC, abstractmethod
class Interface(ABC):
@abstractmethod
def pure_method(self):
pass
●
4.3. Composition
Syntax (C++):
class Engine {
public:
void start() { ... }
};
class Car {
private:
Engine engine; // Car has an Engine
public:
void startCar() { engine.start(); }
};
●
Syntax (Python):
class Engine:
def start(self):
pass
class Car:
def __init__(self):
self.engine = Engine() # Car has an Engine
def start_car(self):
self.engine.start()
●
4.4. Delegation
Syntax (C++):
class Worker {
public:
void performTask() { ... }
};
class Manager {
private:
Worker worker;
public:
void manage() { worker.performTask(); }
};
●
Syntax (Python):
class Worker:
def perform_task(self):
pass
class Manager:
def __init__(self):
self.worker = Worker()
def manage(self):
self.worker.perform_task()
●
Syntax (C++):
class Base {
public:
virtual void show() { cout << "Base"; }
};
int main() {
Base* b = new Derived();
b->show(); // Output: Derived
return 0;
}
●
Syntax (Python):
class Base:
def show(self):
print("Base")
class Derived(Base):
def show(self):
print("Derived")
b = Derived()
b.show() # Output: Derived
●
● Definition: A method for creating objects without specifying the exact class of
object that will be created.
Syntax (C++):
class Product {
public:
virtual void use() = 0;
};
class Creator {
public:
virtual Product* factoryMethod() = 0;
};
class ConcreteCreator : public Creator {
public:
Product* factoryMethod() override { return new ConcreteProduct(); }
};
●
Syntax (Python):
class Product:
def use(self):
pass
class ConcreteProduct(Product):
def use(self):
print("Using ConcreteProduct")
class Creator:
def factory_method(self):
pass
class ConcreteCreator(Creator):
def factory_method(self):
return ConcreteProduct()
●
● Definition: Ensures a class has only one instance and provides a global point of
access to it.
Syntax (C++):
class Singleton {
private:
static Singleton* instance;
Singleton() {}
public:
static Singleton* getInstance() {
if (!instance) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
●
Syntax (Python):
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
●
● Definition: Allows an object to notify other objects about changes in its state.
Syntax (C++):
class Observer {
public:
virtual void update() = 0;
};
class Subject {
private:
vector<Observer*> observers;
public:
void addObserver(Observer* obs) { observers.push_back(obs); }
void notify() {
for (Observer* obs : observers) {
obs->update();
}
}
};
●
Syntax (Python):
class Observer:
def update(self):
pass
class Subject:
def __init__(self):
self._observers = []
def notify(self):
for observer in self._observers:
observer.update()
●
5.4. Example: Decorator Pattern
Syntax (C++):
class Component {
public:
virtual void operation() = 0;
};
Syntax (Python):
class Component:
def operation(self):
pass
class ConcreteComponent(Component):
def operation(self):
print("ConcreteComponent operation")
class Decorator(Component):
def __init__(self, component):
self._component = component
def operation(self):
self._component.operation()
class ConcreteDecorator(Decorator):
def operation(self):
super().operation()
print(" + ConcreteDecorator additional behavior")
●
Certainly! Here’s a continuation of the OOP cheat sheet, diving into more advanced
patterns, exceptions, and additional examples.
Syntax (C++):
class Product {
public:
void setPartA() { /*...*/ }
void setPartB() { /*...*/ }
};
class Builder {
public:
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual Product* getResult() = 0;
};
Syntax (Python):
class Product:
def set_part_a(self):
pass
def set_part_b(self):
pass
class Builder:
def build_part_a(self):
pass
def build_part_b(self):
pass
def get_result(self):
pass
class ConcreteBuilder(Builder):
def __init__(self):
self.product = Product()
def build_part_a(self):
self.product.set_part_a()
def build_part_b(self):
self.product.set_part_b()
def get_result(self):
return self.product
●
Syntax (C++):
class Prototype {
public:
virtual Prototype* clone() const = 0;
};
Syntax (Python):
import copy
class Prototype:
def clone(self):
return copy.deepcopy(self)
class ConcretePrototype(Prototype):
def __init__(self, value):
self.value = value
●
Syntax (C++):
class Strategy {
public:
virtual void execute() = 0;
};
class Context {
private:
Strategy* strategy;
public:
void setStrategy(Strategy* strat) { strategy = strat; }
void doAction() { strategy->execute(); }
};
●
Syntax (Python):
class Strategy:
def execute(self):
pass
class ConcreteStrategyA(Strategy):
def execute(self):
print("Strategy A")
class Context:
def __init__(self, strategy):
self._strategy = strategy
def do_action(self):
self._strategy.execute()
●
● Definition: Passes a request along a chain of handlers, where each handler can
either process the request or pass it along the chain.
Syntax (C++):
class Handler {
protected:
Handler* nextHandler;
public:
Handler() : nextHandler(nullptr) {}
void setNextHandler(Handler* handler) { nextHandler = handler; }
virtual void handleRequest(int request) {
if (nextHandler) nextHandler->handleRequest(request);
}
};
Syntax (Python):
class Handler:
def __init__(self):
self._next_handler = None
class ConcreteHandlerA(Handler):
def handle_request(self, request):
if request < 10:
print("Handled by ConcreteHandlerA")
elif self._next_handler:
self._next_handler.handle_request(request)
●
Syntax (C++):
class Mediator;
class Colleague {
protected:
Mediator* mediator;
public:
void setMediator(Mediator* med) { mediator = med; }
};
class Mediator {
public:
virtual void notify(Colleague* colleague, std::string event) = 0;
};
Syntax (Python):
class Mediator:
def notify(self, colleague, event):
pass
class ConcreteMediator(Mediator):
def __init__(self, colleague1, colleague2):
self._colleague1 = colleague1
self._colleague2 = colleague2
Syntax (C++):
try {
// Code that may throw an exception
throw std::runtime_error("An error occurred");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
}
●
Syntax (Python):
try:
# Code that may throw an exception
raise Exception("An error occurred")
except Exception as e:
print(e)
●
Syntax (C++):
class MyException : public std::exception {
public:
const char* what() const noexcept override {
return "My custom exception";
}
};
try {
throw MyException();
} catch (const MyException& e) {
std::cout << e.what() << std::endl;
}
●
Syntax (Python):
class MyException(Exception):
pass
try:
raise MyException("My custom exception")
except MyException as e:
print(e)
●
8. Additional Examples
8.1. Example: Abstract Factory Pattern
Syntax (C++):
class AbstractFactory {
public:
virtual ProductA* createProductA() = 0;
virtual ProductB* createProductB() = 0;
};
Syntax (Python):
class AbstractFactory:
def create_product_a(self):
pass
def create_product_b(self):
pass
class ConcreteFactory1(AbstractFactory):
def create_product_a(self):
return ProductA1()
def create_product_b(self):
return ProductB1()
class ConcreteFactory2(AbstractFactory):
def create_product_a(self):
return ProductA2()
def create_product_b(self):
return ProductB2()
●
- **Syntax (Python):**
```python
class Command:
def execute(self):
pass
class ConcreteCommand(Command):
def __init__(self, receiver):
self._receiver = receiver
def execute(self):
self._receiver.action()
class Receiver:
def action(self):
pass