100% found this document useful (1 vote)
411 views23 pages

Cheat Sheet Oops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
411 views23 pages

Cheat Sheet Oops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

OOP Cheat Sheet

1. Core OOP Concepts


1.1. Classes and Objects

● 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 : public Base {


public:
void derivedMethod() { ... }
};

Syntax (Python):
class Base:
def base_method(self):
pass

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.

Method Overloading (C++):


class Example {
public:
void display(int i) { ... }
void display(double d) { ... }
};

Method Overriding (C++):


class Base {
public:
virtual void display() { ... }
};

class Derived : public Base {


public:
void display() override { ... }
};

Method Overriding (Python):


class Base:
def display(self):
pass

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 set_age(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.

Abstract Class (C++):


class Abstract {
public:
virtual void pureVirtualFunction() = 0; // Pure virtual function
};

Abstract Class (Python):


from abc import ABC, abstractmethod

class Abstract(ABC):
@abstractmethod
def pure_virtual_method(self):
pass

2. Common OOP Terminology
2.1. Constructor

● Definition: Special method that initializes an object.

Syntax (C++):
ClassName() { ... }

Syntax (Python):
def __init__(self, ...):
...

2.2. Destructor

● Definition: Special method that cleans up when an object is destroyed.

Syntax (C++):
~ClassName() { ... }

Syntax (Python):
def __del__(self):
...

2.3. Access Modifiers

● Definition: Determine the visibility of class members.


● C++:
● public: Accessible from outside the class.
● protected: Accessible within the class and its derived classes.
● private: Accessible only within the class.
● Python:
● _variable: Protected (convention).
● __variable: Private (name mangling).

2.4. Static Members

● 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

2.5. Friend Class (C++)

● 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()

3.2. Example: Inheritance

● Definition:
● Create a base class Animal and a derived class Dog.

C++ Code:
class Animal {
public:
void speak() { cout << "Animal sound"; }
};

class Dog : public Animal {


public:
void bark() { cout << "Woof"; }
};

Python Code:
class Animal:
def speak(self):
print("Animal sound")

class Dog(Animal):
def bark(self):
print("Woof")

3.3. Example: Polymorphism

● Definition:
● Override methods in derived classes.

C++ Code:
class Base {
public:
virtual void show() { cout << "Base class"; }
};

class Derived : public Base {


public:
void show() override { cout << "Derived class"; }
};

Python Code:
class Base:
def show(self):
print("Base class")

class Derived(Base):
def show(self):
print("Derived class")

3.4. Example: Encapsulation

● 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 set_age(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.

OOP Cheat Sheet (Continued)

4. Advanced OOP Concepts


4.1. Multiple Inheritance

● Definition: A class can inherit from more than one base class.

Syntax (C++):
class Base1 {
public:
void method1() { ... }
};

class Base2 {
public:
void method2() { ... }
};

class Derived : public Base1, public Base2 {


public:
void derivedMethod() { ... }
};

Syntax (Python):
class Base1:
def method1(self):
pass

class Base2:
def method2(self):
pass

class Derived(Base1, Base2):


def derived_method(self):
pass

4.2. Interface (Pure Abstract Class)

● Definition: A class with only abstract methods (no implementation).

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

● Definition: Designing a class that contains objects of other classes.

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

● Definition: An object delegates tasks to another object.

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()

4.5. Dynamic Binding

● Definition: The method to be invoked is determined at runtime.

Syntax (C++):
class Base {
public:
virtual void show() { cout << "Base"; }
};

class Derived : public Base {


public:
void show() override { cout << "Derived"; }
};

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

5. Practical Examples and Use Cases


5.1. Example: Factory Method Pattern

● 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 ConcreteProduct : public Product {


public:
void use() override { cout << "Using ConcreteProduct"; }
};

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()

5.2. Example: Singleton Pattern

● 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

5.3. Example: Observer Pattern

● 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 add_observer(self, observer):


self._observers.append(observer)

def notify(self):
for observer in self._observers:
observer.update()

5.4. Example: Decorator Pattern

● Definition: Adds behavior to objects dynamically.

Syntax (C++):
class Component {
public:
virtual void operation() = 0;
};

class ConcreteComponent : public Component {


public:
void operation() override { cout << "ConcreteComponent operation"; }
};

class Decorator : public Component {


protected:
Component* component;
public:
Decorator(Component* comp) : component(comp) {}
void operation() override { component->operation(); }
};

class ConcreteDecorator : public Decorator {


public:
ConcreteDecorator(Component* comp) : Decorator(comp) {}
void operation() override {
Decorator::operation();
cout << " + ConcreteDecorator additional behavior";
}
};

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.

OOP Cheat Sheet (Continued)

6. Design Patterns in OOP


6.1. Builder Pattern

● Definition: Separates the construction of a complex object from its


representation.

Syntax (C++):
class Product {
public:
void setPartA() { /*...*/ }
void setPartB() { /*...*/ }
};

class Builder {
public:
virtual void buildPartA() = 0;
virtual void buildPartB() = 0;
virtual Product* getResult() = 0;
};

class ConcreteBuilder : public Builder {


private:
Product* product;
public:
ConcreteBuilder() { product = new Product(); }
void buildPartA() override { product->setPartA(); }
void buildPartB() override { product->setPartB(); }
Product* getResult() override { return product; }
};

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

6.2. Prototype Pattern

● Definition: Creates a new object by copying an existing object.

Syntax (C++):
class Prototype {
public:
virtual Prototype* clone() const = 0;
};

class ConcretePrototype : public Prototype {


public:
Prototype* clone() const override {
return new ConcretePrototype(*this);
}
};

Syntax (Python):
import copy

class Prototype:
def clone(self):
return copy.deepcopy(self)

class ConcretePrototype(Prototype):
def __init__(self, value):
self.value = value

6.3. Strategy Pattern

● Definition: Defines a family of algorithms, encapsulates each one, and makes


them interchangeable.

Syntax (C++):
class Strategy {
public:
virtual void execute() = 0;
};

class ConcreteStrategyA : public Strategy {


public:
void execute() override { cout << "Strategy A"; }
};

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 set_strategy(self, strategy):


self._strategy = strategy

def do_action(self):
self._strategy.execute()

6.4. Chain of Responsibility Pattern

● 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);
}
};

class ConcreteHandlerA : public Handler {


public:
void handleRequest(int request) override {
if (request < 10) { /* Handle request */ }
else if (nextHandler) nextHandler->handleRequest(request);
}
};

Syntax (Python):
class Handler:
def __init__(self):
self._next_handler = None

def set_next_handler(self, handler):


self._next_handler = handler
def handle_request(self, request):
if self._next_handler:
self._next_handler.handle_request(request)

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)

6.5. Mediator Pattern

● Definition: Defines an object that encapsulates how a set of objects interact.

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;
};

class ConcreteMediator : public Mediator {


private:
Colleague* colleague1;
Colleague* colleague2;
public:
void setColleague1(Colleague* c1) { colleague1 = c1; }
void setColleague2(Colleague* c2) { colleague2 = c2; }
void notify(Colleague* colleague, std::string event) override {
if (colleague == colleague1) { /* Handle event */ }
else if (colleague == colleague2) { /* Handle event */ }
}
};

Syntax (Python):
class Mediator:
def notify(self, colleague, event):
pass

class ConcreteMediator(Mediator):
def __init__(self, colleague1, colleague2):
self._colleague1 = colleague1
self._colleague2 = colleague2

def notify(self, colleague, event):


if colleague == self._colleague1:
# Handle event for colleague1
pass
elif colleague == self._colleague2:
# Handle event for colleague2
pass

7. Exception Handling in OOP


7.1. Exception Handling Basics

● Definition: Mechanism to handle runtime errors.

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)

7.2. Custom Exceptions

● Definition: User-defined exceptions to handle specific errors.

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

● Definition: Creates families of related or dependent objects without specifying


their concrete classes.

Syntax (C++):
class AbstractFactory {
public:
virtual ProductA* createProductA() = 0;
virtual ProductB* createProductB() = 0;
};

class ConcreteFactory1 : public AbstractFactory {


public:
ProductA* createProductA() override { return new ProductA1(); }
ProductB* createProductB() override { return new ProductB1(); }
};

class ConcreteFactory2 : public AbstractFactory {


public:
ProductA* createProductA() override { return new ProductA2(); }
ProductB* createProductB() override { return new ProductB2(); }
};

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()

8.2. Example: Command Pattern

● Definition: Encapsulates a request as an object, thereby allowing


parameterization and queuing of requests.
● Syntax (C++): ```cpp class Command { public: virtual void execute() = 0; };
class ConcreteCommand : public Command { private: Receiver* receiver; public:
ConcreteCommand(Receiver* recv) : receiver(recv) {}

void execute() override { receiver->action(); } };

class Receiver { public: void action() { /* ... */ } };

- **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

You might also like