sheet
sheet
State Pattern
private: - Operator overloading allows class Singleton { class State {
int size; // Number of elements developers to define custom behaviors private: public:
in the sequence for operators when applied to static Singleton* instance; virtual void handle() = 0;
int* elements; // Dynamic array to user-defined types. Singleton() {} // Private constructor virtual ~State() {}
store the sequence - Overloaded operators can be };
public: implemented as member functions or public:
// Constructor non-member (friend) functions. static Singleton* getInstance() { class StateA : public State {
Fibonacci() { 2. **What is the difference between if (instance == nullptr) { public:
size = 0; overloading the `++` operator in prefix instance = new Singleton(); void handle() override {
elements = nullptr; vs. postfix form?** } std::cout << "State A\n";
} - *Answer:* Prefix (`++obj`) return instance; }
// Copy constructor for deep copy increments the value before returning } };
Fibonacci(const Fibonacci& other) { it, while postfix (`obj++`) returns the };
size = other.size; current value before incrementing. class StateB : public State {
if (size > 0) { 3. **Can all operators be overloaded in Singleton* Singleton::instance = nullptr; public:
elements = new int[size]; C++? Provide an example of an ``` void handle() override {
for (int i = 0; i < size; i++) { operator that cannot be overloaded.** **Example:** Database connection std::cout << "State B\n";
elements[i] = - *Answer:* No, not all operators can manager. }
other.elements[i]; be overloaded. For example, the scope ### 2. Composite Pattern };
} resolution operator (`::`) cannot be **Purpose:** Compose objects into tree
} else { overloaded. structures to represent part-whole class Context {
elements = nullptr; **Chapter 24: Inheritance* hierarchies. Enables treating individual private:
} - Inheritance allows a class (derived objects and compositions uniformly. State* state;
} class) to inherit attributes and class Component {
// Assignment operator for deep behaviors from another class (base public: public:
copy class), modeling an "is-a" relationship. virtual void operation() = 0; void setState(State* state) {
Fibonacci& operator=(const - Access specifiers (`public`, `protected`, virtual ~Component() {} this->state = state;
Fibonacci& other) { `private`) in inheritance determine the }; }
if (this != &other) { accessibility of base class members in
delete[] elements; the derived class. class Leaf : public Component { void request() {
size = other.size; - Constructors and destructors in public: state->handle();
if (size > 0) { inheritance follow a specific order: void operation() override { }
elements = new int[size]; base class constructors are called std::cout << "Leaf operation\n"; };
for (int i = 0; i < size; i++) before derived class constructors, and } ### 6. Command Pattern
{ destructors are called in reverse order. }; class Command {
elements[i] = - Function overriding allows a derived public:
other.elements[i]; class to provide a specific class Composite : public Component { virtual void execute() = 0;
} implementation of a function already private: virtual ~Command() {}
} else { defined in its base class. std::vector children; };
elements = nullptr; 1. **What is the significance of the
} `protected` access specifier in public: class Receiver {
} inheritance?** void add(Component* component) { public:
return *this; - *Answer:* `Protected` members are children.push_back(component); void action() {
} accessible within the base class, derived } std::cout << "Action executed\n";
~Fibonacci() { classes, and friend classes, but not from }
delete[] elements; outside these classes. void operation() override { };
} 3. **What is function overriding, and for (Component* child : children) { class ConcreteCommand : public Command {
void generate(int n) { how is it different from function child->operation(); private:
if (n < 0) return; // Handle overloading?** } Receiver* receiver;
invalid input - *Answer:* Function overriding occurs }
delete[] elements; when a derived class provides its own }; public:
size = n; implementation of a function in the ``` ConcreteCommand(Receiver* r) : receiver(r)
elements = new int[size]; base class, using the same name, ### 3. Strategy Pattern {}
if (size > 0) elements[0] = 0; // parameters, and return type. Function class Strategy { void execute() override {
F[0] = 0 overloading, on the other hand, is when public: receiver->action();
if (size > 1) elements[1] = 1; // multiple functions in the same scope virtual void execute() = 0; }
F[1] = 1 have the same name but different virtual ~Strategy() {} };
parameter lists. }; class Invoker {
// Generate remaining numbers **Chapter 25: Polymorphism** private:
for (int i = 2; i < size; i++) { - Polymorphism allows objects of class ConcreteStrategyA : public Strategy { Command* command;
elements[i] = elements[i-1] + different classes to be treated as public: public:
elements[i-2]; objects of a common base class, void execute() override { void setCommand(Command* cmd) {
} providing flexibility in design. std::cout << "Strategy A\n"; command = cmd;
} - Virtual functions enable runtime } }
// Friend function for output polymorphism by allowing derived classes }; void invoke() {
operator overloading to override base class functions. command->execute();
friend ostream& - A pure virtual function (`= 0`) makes class ConcreteStrategyB : public Strategy { }
operator<<(ostream& os, const a class abstract, meaning it cannot be public: };
Fibonacci& fib) { instantiated and is meant to be a base void execute() override { ### 7. Factory Pattern
for (int i = 0; i < fib.size; i++) { class. std::cout << "Strategy B\n"; **Purpose:** Define an interface for
os << "F[" << i << "] = " << - Virtual destructors ensure proper } creating objects but allow subclasses to
fib.elements[i] << endl; cleanup when deleting a derived class }; alter the type of objects created.
} object through a base class pointer. class Product {
return os; 1. **What is runtime polymorphism, and class Context { public:
} how is it achieved in C++?** private: virtual void use() = 0;
}; - *Answer:* Runtime polymorphism Strategy* strategy; virtual ~Product() {}
- A class is a blueprint for creating allows the program to decide at runtime };
objects, defining their attributes which function to invoke for a given public: class ConcreteProductA : public Product {
(member variables) and behaviors object. It is achieved through virtual void setStrategy(Strategy* strategy) { public:
(member functions). functions and pointers or references to this->strategy = strategy; void use() override {
- Classes are typically split into header base class objects. } std::cout << "Product A\n";
files (declarations) and implementation 2. **Why are virtual destructors }
files (definitions) for better important in polymorphic base void executeStrategy() { };
organization. classes?** strategy->execute(); class ConcreteProductB : public Product {
- Static members belong to the class - *Answer:* Virtual destructors ensure } public:
rather than any object instance. that when a derived class object is }; void use() override {
- Friend functions and classes can deleted through a base class pointer, std::cout << "Product B\n";
access private and protected members the derived class's destructor is called, **Example:** Payment processing system }
of another class. preventing resource leaks. (e.g., PayPal, credit card). };
1. **What is a static member variable, 3. **What is a pure virtual function, class Factory {
and how does it differ from a regular and why is it used?** **Usage:** When you need to switch public:
member variable?** - *Answer:* A pure virtual function is between different algorithms dynamically. virtual Product* createProduct() = 0;
- *Answer:* A static member variable a function declared in a base class that ### 4. Prototype Pattern virtual ~Factory() {}
is shared among all instances of a class, must be overridden by derived classes. };
whereas a regular member variable is It is used to define an abstract **Purpose:** Create new objects by
unique to each instance. interface for derived classes. copying an existing object, rather than class FactoryA : public Factory {
2. **How can friend functions access 4. **What happens if a class contains a creating from scratch. public:
private members of a class?** pure virtual function but does not class Prototype { Product* createProduct() override {
- *Answer:* By being declared as a override it in a derived class?** public: return new ConcreteProductA();
friend within the class, granting them - *Answer:* The derived class also virtual Prototype* clone() = 0; }
access to its private and protected becomes abstract, meaning it cannot be virtual ~Prototype() {} };
members. instantiated until it provides }; class FactoryB : public Factory {
implementations for all inherited pure class ConcretePrototype : public Prototype { public:
virtual functions. public: Product* createProduct() override {
Prototype* clone() override { return new ConcreteProductB();
return new ConcretePrototype(*this); }
}