Object Oriented Programming Flashcards

(186 cards)

1
Q

Derived Classes/Child Classes

A

An EXTENSION of a base class Classes that inherit functions and variables from a base class
aka “child” class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Base class/Parent Class

A

Class that can be EXTENDED by a derived class.
Includes functions and variables that can be inherited by a derived class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Inheritance

A

Mechanism for EXTENDING a class
-If you extend the class rather than editing it, you will not have to “re-debug” the original code (because it was not changed since the last time you debugged)
-It allows you to reuse existing DEBUGGED code by allowing a class to acquire properties (data and operations) of another class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Multiple Inheritance

A

Inheritance of properties from multiple classes
-Generally not recommended, but some languages (like C++) will allow it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

“Public”

A

Indicates that the data/operation can interface with the rest of the world
can be accessed from outside of the class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

“Private”

A

Indicates that the data/operation can only interface with member functions of the class in which it was written

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

“Protected”

A

Indicates that the data/operation can ONLY interface with the data/operations of a derived class
DO NOT USE THIS UNLESS YOU KNOW THE CLASS IS GOING TO BE INHERITED (otherwise you can get yourself in trouble when it comes to debugging)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Practical applications of inheritance

A
  1. Principle of Least Privilege & Role-based access control
    The most general base class should have the fewest permissions. As the roles become more specific, they are given more and more privileges.
    2.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Reading a class block in a class diagram

A

Minus (-) inidicates private.
Plus (+) indicates public.
Pound sign (#) indicates “protected”.
The name of the class goes in the top box.
The data/variables of the class go in the middle box.
The operations/functions of the class go in the bottom box.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Inheriting “private” variables/function

A

Private members of the Base Class are present within objects of the Derived Class but are NOT directly accessible within the Derived Class code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Constructors

A

Constructors are not inherited.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Representing a derived class in a UML class diagram

A

Only show what is EXCLUSIVE to the derived class.
NEW variables
NEW functions
Anything that is overwritten

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Memory handling of inheritance

A

When you create a child class, you are also “creating” a parent class inside of that child class. There is a Base class object nested within each Derived class object. The base class object literally comes directly before the derived class in memory. The Base class object “contains” all inherited members

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Accessing private members of the base class

A

If the derived class inherits PUBLIC functions from the base class…. then those functions can still access the private variables of the base class via that public function it just inherited

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Constructor inheritance

A

No such thing. Derived classes do not inherit the constructor from the base class.
You will have to make a new constructor for the derived class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Order in which the destructors are called

A

Destructors are called in the upward inheritance order (less abstract constructors come first) Derived class destructors will be called before the base class destructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Parameters

A

Parameters are needed in the function header. It is a DECLARATION of variables that you can expect to find in that function. They require datatypes just like any declaration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Order in which the constructors are called

A

Constructors are called in the downward inheritance order (more abstract constructors come first) Base class constructors are called before the derived class constructors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Arguments

A

Arguments are needed when the function is CALLED. They represent actual variable names so that you can pass actual values to the function. They do not require datatypes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Calling a function from the based class inside a function of the same name within the derived class

A

This is completely legal. But it you must specify the location of the function you are calling (in C++ this is done using:
base_name::function_name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the purpose/role of the constructor?

A

lol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the purpose/role of the destructor?

A

lol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the sequence of steps the machine goes through when it executes a program that includes both a base class AND a derived class that extends that base class?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Purpose of the #ifndef guard?

A

You NEED it to keep the code from redundant imports. You do not want to import the same file more than once and if you use multiple sourcecode files, it is extremely likely that you have importanted something more than once because some files (like iostream string.h) are included in almost every C++ program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Static Binding
Mean that something is decided how it behaves when you WRITE the code. Compile-time determination of which function to call for a particular object
26
Dynamic Binding
Means that something is decided how it behaves when you EXECUTE the code. Run-time determination of which function to call for a particular object
27
Polymorphism
The ability to determine which of several operations with the same name is appropriate
28
Polymorphic Operation
An Operation that has multiple meanings depending upon the data type of the object to which it is bound at run time
29
Abstract Data Type
Data type whose properties (domain and operations) are specified independently of any implementation
30
Class
–A structured type used to model abstract data types –Encapsulate attributes (data) with the member functions that modify the attribute values
31
Object
–An instance of a class –Set of attribute values define the state of an object at a given time –Member functions and attributes accessed using the member selection operator (period .)
32
Client
–Software that declares and manipulates objects of a particular class type
33
public members of a class
Can be accessed from outside of the class
34
private members of a class
Accessible only by the code within the implementation file and is not accessible by code outside of the class - Client cannot interact directly with private variables or functions within object
35
Specification file
*The declaration of the class type *Include guards (more on this later)
36
Implementation File
*Code that implements the member functions of the class
37
Unit Testing
- Performed with a dedicated driver program –Contains a simplified main function that creates instances of the class (objects) and then tests the objects by using its public interface –Multiple source files must be compiled and linked to create the executable –Once tested, the class may be reused with the actual application program
38
struct v. class
–A struct is a class whose members are public by default –By default, all members of a C++ class are private –Two built-in operations for structs and classes "." and "="
39
Five categories of member functions
1. Constructors 2. Transformers 3. Observers 4. Iterators 5. Destructors
40
Constructor functions in a C++ class
Create and Initialize Object Constructor methods have the same name as the class
41
Transformers functions in a C++ class
Alter the state of an object
42
Observer functions in a C++ class
Allow one to view the state of an object
43
Iterator functions in a C++ class
Allow us to process (one at a time) all components of an ADT
44
"const" for member functions
Member functions applied to an object may alter attributes stored within that object unless the reserved word const is used to prevent modification
45
"self" for member functions
The object to which a member function is applied
46
What is the **big picture purpose** of OOP?
OOP is about organizing code around **objects** that bundle **data + behavior** ## Footnote It models parts of the real/abstract world in ways that are easier to reason about, extend, and maintain.
47
What are the **basic building blocks** of OOP?
* Objects * Classes * Interfaces ## Footnote These are fundamental concepts that form the structure of object-oriented programming.
48
An **object** consists of what three components?
* State * Behavior * Identity ## Footnote State refers to data/fields/attributes, behavior refers to methods/functions, and identity distinguishes between different objects.
49
In **class-based OOP**, what does a class define?
The structure (fields) and behavior (methods) for all its instances ## Footnote Examples include languages like C++, Java, and C#.
50
What does an **interface** express in OOP?
Anything that behaves like this can be used here ## Footnote Examples include `IStream`, `Shape`, `ILogger`, etc.
51
What are the **classic four** principles of OOP?
* Encapsulation * Abstraction * Inheritance * Polymorphism ## Footnote These principles guide the design and implementation of object-oriented systems.
52
Define **encapsulation** in OOP.
Group related data + behavior and hide internal details behind a clean interface ## Footnote This involves using visibility modifiers and not exposing internal fields directly.
53
What is the focus of **abstraction** in OOP?
Focus on what something *does*, not how it does it ## Footnote This allows for defining abstract concepts and operating on them instead of concrete details.
54
What does **inheritance** create between types?
An *'is-a'* relationship ## Footnote For example, `class Rectangle : public Shape` indicates that Rectangle is a type of Shape.
55
What is the core power of **polymorphism**?
Code that works with many concrete types via a single interface/abstract type ## Footnote This allows for extending behavior without rewriting existing code.
56
What is the guideline for **composition over inheritance**?
Use composition when you want to combine behaviors flexibly ## Footnote This approach leads to less rigid coupling and easier testing.
57
What does **Single Responsibility** mean in the context of SOLID principles?
A class should have **one reason to change** ## Footnote This improves testability, reusability, and readability.
58
What is **cohesion** in class design?
Things inside a class should **naturally belong together** ## Footnote High cohesion indicates that the class has a clear purpose.
59
What does **coupling** refer to in OOP?
How dependent classes are on each other ## Footnote Minimizing tight coupling is essential for maintainable code.
60
List the **SOLID principles**.
* Single Responsibility * Open/Closed * Liskov Substitution * Interface Segregation * Dependency Inversion ## Footnote These principles guide the design of maintainable and scalable object-oriented systems.
61
What should you understand about **object lifecycle**?
* Creation * Initialization * Lifetime * Destruction ## Footnote This includes understanding constructors, destructors, and memory management.
62
What is the difference between **overriding** and **overloading**?
* Overriding: same signature in subclass, different implementation * Overloading: same name, different parameter list ## Footnote These concepts are crucial for understanding method resolution in OOP.
63
What are the characteristics of **value type semantics**?
* Copying the object copies its data * Mutating one copy doesn’t affect the other ## Footnote This contrasts with reference semantics where variables refer to shared underlying objects.
64
Good OOP should make **testing easier**, not harder. What are key ideas related to testing?
* Minimize responsibilities * Use dependency injection * Favor interfaces and composition ## Footnote This helps in creating testable and maintainable code.
65
Identify a common **OOP anti-pattern**.
* God Object * Anemic Domain Model * Deep inheritance hierarchies * Excessive getters/setters * Overuse of singletons/global state ## Footnote Recognizing these patterns is crucial for effective design.
66
What is the **procedural style** in programming?
Data structures + functions that operate on them ## Footnote This style is great for small scripts and simple pipelines.
67
What are some **creational design patterns**?
* Factory * Abstract Factory * Builder * Singleton ## Footnote These patterns help in object creation mechanisms.
68
What should a strong engineer be able to **do** with OOP?
* Explain core concepts * Design OO models * Refactor code * Write tests * Reason about performance & memory * Balance OOP usage ## Footnote Mastery of these skills is essential for effective software engineering.
69
What are the **four components** that define an **object** in OOP?
* State * Behavior * Identity * Layout ## Footnote Understanding these components is essential for grasping the mechanics of object-oriented programming.
70
In memory layout, what is typically found at the start of an object in C++?
Optional **vptr** (virtual table pointer) ## Footnote This is followed by member fields and possibly padding for alignment.
71
True or false: **Subclassing** and **subtyping** are the same.
FALSE ## Footnote Subclassing refers to implementation inheritance, while subtyping refers to type compatibility.
72
What does the **Liskov Substitution Principle (LSP)** state?
Replacing `Base` with `Derived` does not change observable behavior ## Footnote This principle formalizes the relationship between subtyping and behavior contracts.
73
What is the purpose of a **vtable** in OOP?
A table of function pointers for dynamic dispatch ## Footnote Each class with virtual methods has a vtable, and each object has a vptr pointing to its class's vtable.
74
What is the **diamond problem** in multiple inheritance?
Ambiguous base class subobjects without virtual inheritance ## Footnote This occurs when a derived class inherits from two classes that share a common base class.
75
What does **RAII** stand for in C++?
Resource Acquisition Is Initialization ## Footnote This principle ties resource management to object lifetime.
76
In C++, what are the two types of storage for objects?
* Automatic storage (stack) * Dynamic storage (heap) ## Footnote Understanding these storage types is crucial for managing object lifetimes.
77
What is the difference between **dynamic** and **static polymorphism**?
* Dynamic: runtime dispatch * Static: compile-time dispatch ## Footnote Dynamic polymorphism uses interfaces/virtual functions, while static polymorphism uses templates or generics.
78
What is **object slicing** in C++?
Only the base part of a derived object is copied when passed by value ## Footnote This leads to loss of polymorphic behavior.
79
What is the **actor model** in concurrency?
Each object/thread has exclusive mutable state; others communicate via messages ## Footnote This model helps avoid shared mutable state issues.
80
What are the **two types of inheritance** in C++?
* Single inheritance * Multiple inheritance ## Footnote Understanding these types is essential for designing class hierarchies.
81
What is the **purpose of encapsulation** in OOP?
Hiding internal representation + enforcing invariants through a stable interface ## Footnote Good encapsulation practices prevent unintended interactions with an object's state.
82
What does **covariance** refer to in function types?
Derived return type is acceptable when overriding ## Footnote This allows for more specific return types in derived classes.
83
What does **contravariance** refer to in function types?
Base parameter type is acceptable when overriding ## Footnote This allows for more general parameter types in derived classes.
84
What is the **goal of good OOP** from a compiler and runtime perspective?
* Stable interfaces * Predictable call graph * Clear ownership and lifetime ## Footnote These goals help reduce recompilation needs and improve performance.
85
What is a common pattern for using **multiple inheritance**?
* For interfaces (pure virtual base classes) * Single concrete base for shared implementation ## Footnote This approach helps avoid complexity and ambiguity in class hierarchies.
86
What are the key concepts to understand regarding **subtyping**?
* Dynamic dispatch (vtable/vptr) * Object layout with single and multiple inheritance ## Footnote Understanding these concepts is crucial for effective object-oriented programming.
87
What should a small class hierarchy respect according to **LSP**?
* Use composition where appropriate * Interfaces narrow enough for Interface Segregation ## Footnote LSP stands for Liskov Substitution Principle, which is essential for maintaining code correctness.
88
When should you use **dynamic vs static polymorphism**?
Know when to use each ## Footnote Understanding the differences helps in making informed design decisions.
89
What is a common issue to avoid in C++ related to **object slicing**?
Avoid object slicing ## Footnote Object slicing occurs when an object of a derived class is assigned to an object of a base class.
90
What design considerations should be made for **lifetime management** in C++?
* Design RAII types * Choose proper smart pointer types * Implement or delete copy/move correctly ## Footnote RAII stands for Resource Acquisition Is Initialization, a key concept in C++ for resource management.
91
In garbage-collected languages, what should be avoided regarding **object graphs**?
Avoid unbounded object graphs ## Footnote This helps in preventing memory leaks and performance issues.
92
What is important to understand about **variance** in type systems?
* `List` is not `List` * Design APIs around this understanding ## Footnote Variance affects how types relate to one another in inheritance hierarchies.
93
When should you consider **optimizing** your object-oriented design?
* When object graphs and virtual calls are a bottleneck * Reshape hot paths with more data-oriented or functional patterns ## Footnote Optimization should be based on profiling and identifying performance issues.
94
What is a suggested approach to design an **OO model** for a concrete mini-problem?
* Design it twice: once as 'naive OOP', once as 'technically sound OOP' ## Footnote This includes vtable-aware decisions, lifetime considerations, and performance considerations.
95
Four Pillars of OOP
Encapsulation Abstraction Inheritance Polymorphism
96
# inheritabnce What is **encapsulation** in terms of guarantees?
* Representation can change without breaking callers * Invariants are preserved * Interactions go through constrained choke points ## Footnote Encapsulation is a set of guarantees that maintain the integrity of an object's state and behavior.
97
What kinds of **internals** are encapsulated?
* Representation * Invariants * Dependencies * Performance characteristics ## Footnote Encapsulation applies to various aspects of an object's internal workings.
98
Name the **access modifiers** used to enforce encapsulation.
* public * protected * private * Package/internal visibility ## Footnote Different programming languages have specific keywords to control access to class members.
99
What is the **PIMPL idiom** in C++?
* Exposes only the interface of a class * Implementation details are hidden in a separate struct * Hides member fields and choice of containers ## Footnote PIMPL stands for Pointer to Implementation, a technique to achieve encapsulation at the binary level.
100
True or false: **Direct field exposure** is a good practice in encapsulation.
FALSE ## Footnote Directly exposing fields can lead to breaking invariants and compromising the integrity of the object's state.
101
What are **invariants** in the context of encapsulation?
* Valid ranges * Cross-field relationships * Protocol state ## Footnote Invariants are conditions that must always hold true for an object to maintain its valid state.
102
What does **Design by Contract** involve?
* Preconditions * Postconditions * Class invariants ## Footnote Design by Contract is a methodology that specifies the obligations and guarantees of software components.
103
What are the two types of objects in relation to **mutation**?
* Immutable * Mutable ## Footnote Immutable objects cannot be modified after creation, while mutable objects can change state.
104
What should be checked to avoid **representation exposure**?
* No internal fields should be public * No getters returning mutable references * No direct modifications to internal containers ## Footnote Ensuring these conditions helps maintain encapsulation and protect invariants.
105
What are the **scales** at which encapsulation applies?
* Class-level * Module/namespace-level * Service-level ## Footnote Encapsulation principles can be applied at various levels of software architecture.
106
List some **practical encapsulation heuristics**.
* List invariants for each class * Check for representation exposure * Push behavior to data * Check the surface area of public methods * Review module/service contracts * Ensure testability through public API * Assess concurrency ownership ## Footnote These heuristics help in analyzing and improving encapsulation in code.
107
What is the difference between **abstraction** and **encapsulation**?
* Encapsulation: hiding representation + controlling access to state * Abstraction: hiding irrelevant detail to present a simpler conceptual model ## Footnote Encapsulation preserves invariants, while abstraction simplifies the model.
108
Abstraction involves a mapping from **concrete mechanisms** to a **conceptual model**. What are the steps involved in this mapping?
* Selecting relevant aspects * Forgetting / hiding irrelevant aspects * Naming the concept * Stabilizing it as a contract ## Footnote This process helps define what details are internal mechanisms and what is exposed to clients.
109
Name the **kinds of abstraction** by mechanism.
* Procedural abstraction * Data abstraction / ADTs * Subtype / interface abstraction * Parametric abstraction * Module / component abstraction ## Footnote Each type serves a different purpose in hiding complexity.
110
What is **procedural abstraction**?
Hiding how something is done behind a function/method ## Footnote Clients know the procedure's signature and contract but not the internal workings.
111
What does **data abstraction** (ADTs) hide?
The internal representation of data structures behind operations ## Footnote Clients interact with the data structure through defined operations without knowing the implementation.
112
What is the purpose of **subtype / interface abstraction**?
Define a behavior contract and hide concrete implementing types behind it ## Footnote Clients depend on the interface, not the specific implementations.
113
What is **parametric abstraction**?
Parameterizing code over types/values, abstracting over what is stored rather than how ## Footnote This allows for flexibility in the types used without changing the underlying implementation.
114
What does **module / component abstraction** involve?
Grouping related types + functions and exposing a narrow public interface ## Footnote This hides the internal details of the module while providing a clear interface for interaction.
115
How does OOP encode **abstraction**?
* Interfaces * Abstract classes * Polymorphism ## Footnote These constructs allow for defining operations without specifying implementations.
116
What are the **levels of abstraction**?
* Low-level abstraction * Mid-level abstraction * High-level / domain abstraction ## Footnote Each level hides more implementation detail and uses the layers below as mechanisms.
117
What are **behavioral contracts** in abstraction?
Specifications of pre- and post-conditions for operations ## Footnote Clients rely on these behaviors rather than implementation details.
118
What is a **leaky abstraction**?
An abstraction that does not fully hide underlying complexity, requiring clients to understand internals ## Footnote Examples include TCP and ORMs where clients must deal with underlying issues.
119
What is **over-abstraction**?
Too many layers or too generic abstractions that complicate understanding ## Footnote Symptoms include hard-to-trace logic and excessive boilerplate.
120
What is **under-abstraction**?
Too concrete; exposing implementation details everywhere ## Footnote This leads to difficulties in changing implementations and testing.
121
What should you start with when designing abstractions?
* Operations * Invariants ## Footnote This helps define what the abstraction should do and what must always be true.
122
What is a good practice regarding **abstraction surfaces**?
Keep them small and stable ## Footnote Aim for small, focused interfaces and a minimal public API.
123
What is the goal of designing for **readability** at call sites?
Ensure top-level code reads like business/domain language, not low-level calls ## Footnote This improves clarity and understanding of the code.
124
What is the nature of **abstraction** in software design?
Iterative; it evolves from concrete to abstract as patterns emerge ## Footnote Continuous refactoring helps refine abstractions over time.
125
What is the first step in the **abstraction** process?
Start concrete and specific ## Footnote Abstraction is rarely right on the first try; it begins with concrete examples.
126
What do you do as you see **repetition and patterns** in abstraction?
Factor into abstractions ## Footnote Recognizing patterns allows for the creation of more generalized abstractions.
127
What should you do when an abstraction becomes too **generic and confusing**?
Simplify ## Footnote Simplification is necessary to maintain clarity in abstractions.
128
How does **TDD** (Test-Driven Development) assist in the abstraction process?
Tests nail behavior, reshape implementation and abstractions ## Footnote TDD helps ensure that the behavior remains consistent while refactoring.
129
What is the first step in the suggested next steps for continuous refactoring?
Pick a concrete domain ## Footnote Examples of domains include job scheduler, payments, or game entities.
130
In the next steps for continuous refactoring, what is the second step after modeling with naive, leaky abstractions?
Iteratively refactor into cleaner abstractions ## Footnote This step focuses on improving the initial abstractions for better clarity and functionality.
131
What is the third step in the continuous refactoring process?
Map each abstraction back to decomposed categories ## Footnote Categories include procedural, data, subtype, module, etc.
132
What is the **literal meaning** of polymorphism?
Many forms ## Footnote In programming, it refers to a function/operation/variable working with values of different types through a single interface.
133
Name the **main kinds** of polymorphism.
* Parametric polymorphism * Subtype polymorphism * Ad-hoc polymorphism * Coercion polymorphism ## Footnote This classification is based on the classic taxonomy by Cardelli & Wegner.
134
What is **subtype polymorphism**?
One interface, many concrete implementations ## Footnote If B is a subtype of A, a value of B can be used where A is expected.
135
What does the **Liskov Substitution Principle (LSP)** state?
B is a proper subtype of A if every property proven about A holds when B is used instead ## Footnote This principle ensures polymorphic OOP APIs are safe.
136
What is the **core idea** of parametric polymorphism?
Write a function/type once, and it works for any type(s) that satisfy constraints ## Footnote Example: `template T maxValue(const T& a, const T& b)`.
137
What are the two major strategies for implementing **parametric polymorphism**?
* Monomorphization * Type erasure ## Footnote Monomorphization generates concrete copies for each type, while type erasure uses a single implementation with a placeholder type.
138
What is **ad-hoc polymorphism**?
Behavior differs for specific type combinations ## Footnote It includes function overloading, operator overloading, and type classes.
139
What is the difference between **single dispatch** and **multiple dispatch**?
* Single dispatch: method chosen based on runtime type of the receiver * Multiple dispatch: method chosen based on runtime types of all arguments ## Footnote Most mainstream OOP languages use single dispatch.
140
What is **coercion polymorphism**?
Polymorphism via automatic type conversion ## Footnote Example: `int + double` where int is converted to double.
141
What are the two types of **dispatch strategies**?
* Static dispatch * Dynamic dispatch ## Footnote Static dispatch decisions are made at compile time, while dynamic dispatch decisions are made at runtime.
142
What is the difference between **nominal** and **structural subtyping**?
* Nominal: types are related if they explicitly declare the relationship * Structural: types are related if their shape matches ## Footnote Nominal subtyping relies on names, while structural subtyping relies on method signatures.
143
What are some **design patterns** that utilize polymorphism?
* Strategy * State * Visitor * Factory ## Footnote These patterns structure dispatch and type variation in object-oriented design.
144
What are the **costs** associated with subtype polymorphism?
* Indirect calls * Slower than direct calls * Harder for compiler to inline ## Footnote These costs can affect performance and optimization.
145
What is a **pitfall** of using `switch` on type tags?
It breaks the open/closed principle ## Footnote Adding a new type requires editing every switch, which is not a real polymorphism.
146
What is a **heuristic** for choosing which polymorphism to use?
Do I need runtime variation / plugins / user-configurable behavior? ## Footnote If yes, consider subtype polymorphism or dynamic dispatch.
147
What is the **overridden method** that sometimes throws?
Base method that accepts a range, derived method that only accepts small subset ## Footnote This breaks polymorphism in a logical sense, even if the compiler is fine with it.
148
When designing code, what should you ask to determine if you need **runtime variation / plugins / user-configurable behavior**?
Yes → subtype polymorphism or dynamic dispatch ## Footnote Example: payment providers, storage backends.
149
If you just need **generic containers/algorithms**, what should you choose?
Yes → parametric polymorphism (templates/generics) ## Footnote Example: collections, algorithms, math utilities.
150
What should you use if you want **distinct functions for different types but a shared name**?
Yes → overloading/ad-hoc polymorphism ## Footnote Example: `print(int)`, `print(string)`.
151
If the variation is purely **syntactic (numbers vs numbers)**, what may be fine?
Coercion or overloading ## Footnote This approach simplifies the handling of similar types.
152
If **performance is critical**, what should you prefer?
Prefer parametric/static polymorphism for hot loops ## Footnote Reduce dynamic dispatch on critical paths.
153
If the problem is about **data shapes and transformations**, what should you consider?
Maybe don’t use OO subtype polymorphism at all ## Footnote Consider using algebraic data types + pattern matching, or data-oriented design.
154
What are the three versions you can design side-by-side for a small but non-trivial domain?
* Subtype-based polymorphic solution * Parametric/generic solution * Ad-hoc/overload or pattern-matching solution ## Footnote Compare their extensibility, performance, and complexity.
155
What is the **conceptual definition** of inheritance?
A mechanism that lets you define a new type (the 'derived' / 'subclass') by reusing and extending the definition of an existing type (the 'base' / 'superclass') ## Footnote Inheritance is primarily a code reuse and relationship mechanism.
156
Inheritance is primarily a **code reuse and relationship mechanism**. What does it allow?
* Derived class reuses the base’s fields * Derived class reuses the base’s methods * Derived class may reuse base invariants ## Footnote Inheritance is not synonymous with subtyping or polymorphism.
157
True or false: Inheritance is synonymous with **subtyping**.
FALSE ## Footnote Subtyping can exist without inheritance, and inheritance can exist without proper subtyping.
158
What are the two main types of **inheritance**?
* Interface inheritance * Implementation inheritance ## Footnote Interface inheritance involves a type promising to support a set of operations, while implementation inheritance involves inheriting actual code and data layout.
159
What is **interface inheritance**?
A type promises it supports a certain set of operations (a contract), but may not inherit any implementation ## Footnote Examples include Java interfaces and C++ pure virtual base classes.
160
What is **implementation inheritance**?
A type inherits actual code and data layout from its base class ## Footnote This allows derived classes to reuse implementation and layout.
161
What is the **diamond inheritance problem**?
Occurs when a derived class inherits from two base classes that share a common ancestor, leading to ambiguity ## Footnote Example: A derived class has two base classes that each contain a member from the common ancestor.
162
What is the order of **constructor and destructor** calls in single inheritance?
1. Base class constructor 2. Member fields (in declaration order) 3. Derived class constructor body ## Footnote Destruction order is the reverse.
163
What is the difference between **overriding** and **overloading**?
* Overriding: Same signature in base and derived * Overloading: Same name, different parameter types or count ## Footnote Overriding is resolved at runtime, while overloading is resolved at compile time.
164
What are **abstract classes**?
Classes that cannot be instantiated and contain abstract (pure virtual) methods that must be implemented by subclasses ## Footnote They serve as a combined interface and partial implementation base.
165
What is the **fragile base class problem**?
Occurs when a subclass depends on base implementation details, leading to breakage when the base class is modified ## Footnote Mitigation strategies include designing base classes with explicit extension points.
166
When should you use **inheritance**?
* Clear, stable 'is-a' relationship * Base type designed explicitly for extension * Need runtime polymorphism ## Footnote Examples include `AdminUser is a User`.
167
When is **composition** preferred over inheritance?
* Reuse functionality without exposing 'is-a' relationship * Swap behavior at runtime * Break coupling ## Footnote Examples include a `UserService` having a `UserRepository`.
168
What is the **Liskov Substitution Principle (LSP)**?
A function that works for Base must continue to work when given any Derived ## Footnote Violations include strengthening preconditions or weakening postconditions.
169
What is **covariant return types**?
Allows a derived method to return a more specific type than the base method ## Footnote This is useful but must be understood as still overriding.
170
What is the purpose of **mixins**?
Classes intended to be inherited from to add behavior, not necessarily to represent an 'is-a' relationship ## Footnote Example: A SerializableMixin adds serialization behavior.
171
What is **prototypal inheritance**?
A form of object-level inheritance where objects inherit from other objects via prototype chains ## Footnote JavaScript uses this mechanism, allowing for dynamic behavior.
172
What is the purpose of **breaking coupling** in software design?
* Use interfaces * Dependency injection * Avoid inheriting heavy base classes ## Footnote Breaking coupling enhances flexibility and maintainability in code.
173
Define **composition** in the context of software design.
* “Has-a” relationship * “Uses-a” via delegation ## Footnote Composition allows for building complex types by combining simpler ones.
174
What are the characteristics of **C++** regarding inheritance?
* Full multiple inheritance * Virtual inheritance * Manual control over virtual functions * RAII + destructors ## Footnote C++ provides powerful features for managing inheritance and object lifetimes.
175
In **Java / C#**, what type of inheritance is allowed for classes and interfaces?
* Single inheritance for classes * Multiple inheritance for interfaces ## Footnote Java and C# handle inheritance differently, especially with interfaces.
176
What is the **Method Resolution Order (MRO)** in Python?
Defined order for resolving method calls in multiple inheritance ## Footnote MRO ensures a consistent method resolution path in Python's multiple inheritance.
177
Describe the inheritance model in **JavaScript**.
* Prototypal inheritance * ES6 class syntax sugar ## Footnote JavaScript uses prototypes for inheritance, with classes being a syntactical convenience.
178
What is the inheritance approach in **Go**?
* No class inheritance * Interfaces + struct embedding ## Footnote Go emphasizes composition over inheritance, using interfaces for type definitions.
179
What is the first question in the **inheritance review checklist**?
**Is this really an “is-a”?** ## Footnote This question helps determine if inheritance is appropriate or if composition should be considered.
180
What should you check regarding the **base class** in inheritance?
* Virtual destructor (C++)? * Clear documentation? * Stable contract (LSP respected)? ## Footnote Ensuring the base class is designed for inheritance is crucial for maintaining a robust hierarchy.
181
What does it indicate if a derived class **overrides behavior** rather than just adding new methods?
Composition may be simpler ## Footnote If a derived class primarily adds new behavior, it may be more efficient to use composition.
182
What does heavy use of **protected members** in a class suggest?
Strong coupling to base internals ## Footnote Excessive protected members can indicate a tightly coupled design that may need refactoring.
183
What is the implication if an inheritance chain does not respect **Liskov Substitution Principle (LSP)**?
Need to break the hierarchy or separate interfaces ## Footnote Violating LSP can lead to unexpected behaviors in derived classes.
184
What should you avoid when designing a **base class**?
* Mixing unrelated concerns * Sharing code just to reuse methods ## Footnote Keeping concerns separate can lead to cleaner and more maintainable code.
185
What is a potential downside of using inheritance in terms of **testing derived classes**?
Inheritance brings unwanted behavior or dependencies ## Footnote This can complicate testing and indicate that inheritance may not be the best design choice.
186
What is a suggested next step after analyzing an inheritance hierarchy?
* Analyze interface vs. implementation inheritance * Check LSP * Identify fragile base class risks ## Footnote Systematic analysis can lead to better design decisions regarding inheritance and composition.