0% found this document useful (0 votes)
2 views23 pages

oop_cpp_god

This cheat sheet provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, including classes, objects, constructors, access modifiers, and the four main principles: encapsulation, abstraction, inheritance, and polymorphism. It explains key features such as exception handling, templates, structures, enums, and unions, along with their differences and use cases. The document emphasizes the importance of OOP in simplifying complex problems, promoting code reuse, and enhancing data security.
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
0% found this document useful (0 votes)
2 views23 pages

oop_cpp_god

This cheat sheet provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, including classes, objects, constructors, access modifiers, and the four main principles: encapsulation, abstraction, inheritance, and polymorphism. It explains key features such as exception handling, templates, structures, enums, and unions, along with their differences and use cases. The document emphasizes the importance of OOP in simplifying complex problems, promoting code reuse, and enhancing data security.
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

Object Oriented Programming Cheat Sheet

OBJECT ORIENTED

When getting ready for a software engineering interview, remember


that in addition to being familiar with the specific technology related
to the job, you should also be well-versed in fundamental Object-
Oriented Programming concepts.

Object oriented programming:


Object-Oriented Programming (OOP) is a programming paradigm
centered around the concept of objects, which bundle data and
methods to model real-world entities and their interactions.

Class:
A blueprint for creating
objects that encapsulates data
(attributes) and functions
(methods) to operate on the
data. The class does not
consume memory at runtime.

Object:
An object is a concrete instance of a class. While a class defines the
structure and behavior
(data and methods) that
objects created from it

1
Object Oriented Programming Cheat Sheet

will have, an object is a specific realization of that class, containing


actual values and state.

Constructor:
A constructor is a special member function in a class used to initialize
objects of that class. It is called automatically when an object is
created and is responsible for setting up the initial state of the
object.

Default constructor:

Parameterized constructor:

Copy constructor:

Move constructor: (C++11 and


later)

2
Object Oriented Programming Cheat Sheet

Access modifiers:
Access modifiers in Object-Oriented Programming (OOP) are keywords
used to specify the accessibility or visibility of class members
(attributes and methods) from
outside the class.

• Public: Used for methods and


attributes that need to be
accessed from outside the
class.

• Private: Used for data


members and methods that
should be hidden from other
classes and functions to
prevent unintended
interference.

• Protected: Used to
allow derived classes to
access and modify
certain members while
still keeping the hidden

3
Object Oriented Programming Cheat Sheet

from non-derived classes.

Main principles of OOPs:

1. Encapsulation
2. Abstraction
3. Inheritance
4. polymorphism

Encapsulation:
Involves bundling data and methods within a class, and controlling
access to the data through access modifiers. It promotes data hiding,
enhances security, and
improves maintainability and
flexibility in code. It involves
restricting direct access to
some of the object's
components, which is intended
to prevent unintended
interference and misuse of
the object's internal state. The data and the operations that
manipulate the data are contained within the same structure, creating
a cohesive unit.

4
Object Oriented Programming Cheat Sheet

Key Points of Encapsulation

Data Hiding: Restricts direct access to an object's internal state,


exposing only what is necessary through public methods.

Access Modifiers: Uses keywords like private, protected, and public to


control visibility and access to class members.

Getter and Setter Methods: Provides controlled access to private data


members, allowing validation and encapsulation of logic.

Improved Security: Protects object integrity by preventing unintended


interference and misuse of data.

Modularity: Promotes separation of concerns, making the code base


easier to manage and understand.

Maintainability: Simplifies modifications by isolating changes to a


specific class without affecting other parts of the program.

Abstraction:
Helps manage complexity by hiding the detailed implementation of
objects and exposing only the essential features that are relevant for
interaction.

5
Object Oriented Programming Cheat Sheet

Interface vs. Implementation: Abstraction involves defining an


interface (what an object does) while hiding the implementation details
(how it does it). For instance, when you use a car, you interact with it
through controls like the steering wheel and pedals, but you don’t need
to understand the intricate workings of the engine or transmission.

Key points:

Simplified Interface: Hides complex implementation details, exposing


only essential features and interfaces.

6
Object Oriented Programming Cheat Sheet

Improved Code Maintainability: Facilitates changes in the


implementation without affecting the code that uses the abstracted
interface.

Encapsulation Support: Works hand-in-hand with encapsulation to group


related data and methods into cohesive units.

Abstract Classes and Methods: Defines abstract classes with pure virtual
functions to establish a common interface for derived classes.

Modular Design: Promotes modularity by defining clear, reusable


interfaces and separating concerns.

Inheritance:
Inheritance in object-oriented programming (OOP) is a mechanism that
allows one class (the derived class) to acquire properties and behaviors
(methods) from another class (the base class). It promotes code reuse
and establishes a natural hierarchy between classes.

Key points:

Code reusability: allows you to reuse code from an existing class, reducing
redundancy.

Hierarchical Relationships: It creates a hierarchy where a derived class (child)


inherits attributes and methods from a base class (parent). This reflects a "is-a"
relationship. For example, a Dog is a Animal.

Types of inheritance:

• Single inheritance: A class inherit from a one base class.


• Multiple inheritance: A class inherits from more than one base class.
• Multilevel inheritance: A class inherits from another derived class.
• Hierarchical inheritance: Multiple classes inherit from a single base class.

7
Object Oriented Programming Cheat Sheet

Access specifiers:

• Public inheritance: Public members of the base class remain public in the
derived class.
• Private inheritance: Public and protected members of the base class become
private in the derived class.
• Protected inheritance: Public members of the base class become protected in
the derived class.

Method overriding:

8
Object Oriented Programming Cheat Sheet

Polymorphism:
It allows objects of different classes to be treated as objects of a common base class,
particularly through the use of methods with the same name but different
implementations.

Types of polymorphism:

• Compile-time polymorphism (static polymorphism)


• Run-time polymorphism (dynamic polymorphism)

Compile-Time Polymorphism:

Compile-time polymorphism is achieved through function overloading and operator


overloading.

Function Overloading

Function overloading allows you to have


multiple functions with the same name but
different parameters (different signatures)
within the same scope. The function that is
called is determined at compile time based on
the function signature.

Operator Overloading

Operator overloading allows you to define custom behavior for operators (like +, -, *, etc.)
for user-defined classes.

9
Object Oriented Programming Cheat Sheet

Run-time polymorphism:

Run-time polymorphism is achieved through inheritance and virtual functions. This allows
the program to decide which method to call at run-time based on the object’s type.

Virtual Functions

A virtual function is a member function in a base class that you can override in a derived
class. The virtual keyword is used to indicate that the function can be overridden.

10
Object Oriented Programming Cheat Sheet

(Abstract class) Pure Virtual Functions

A pure virtual function is a virtual function that is declared by assigning 0 in its


declaration. This makes the class abstract, meaning it cannot be instantiated.

AbstractBase has a pure virtual function, making it an abstract class. ConcreteDerived


provides an implementation for this function.

Key Points of Polymorphism

Compile-Time Polymorphism: Achieved through function and operator overloading;


resolved at compile time.

Run-Time Polymorphism: Enabled by virtual functions and inheritance; method


resolution occurs at runtime based on the object type.

Dynamic Binding: Allows functions to be called based on the actual object type,
enhancing flexibility.

Abstract Classes: Define interfaces with pure virtual functions, forcing derived classes
to implement specific behavior.

Code Reusability: Promotes writing generic code that works across different derived
classes.

11
Object Oriented Programming Cheat Sheet

Maintenance: Simplifies code management and facilitates easier updates and


extensions.

What is the difference between data abstraction and


encapsulation?
Aspect Data abstraction Encapsulation

definition Hiding complex Bundling data and methods


implementation details and that operate on that data
showing only essential within a single unit class
features
Focus Focus on what an object Focuses on how the data is
does.(behavior) protected and accessed
Implementation Achieved through abstract Achieved using access
classes and interfaces modifiers (private, public,
protected) to restric access
to class members
Purpose To reduce complexity and To protect the object’s
increase efficiency by state and ensure data
simplifying the interfaces integrity

Exception:
Exceptions provide a way to handle errors and other exceptional conditions that occur
during the execution of a program. They help you manage unexpected situations without
using error codes and improve the robustness and readability of your code.

Basics of exception:

Throwing exception:
Use the throw keyword to signal that an error or exceptional condition has occurred.

Try catch block:

12
Object Oriented Programming Cheat Sheet

Use the try block to write code that might throw an exception and catch blocks to handle
specific types of exceptions.

Multiple catch block:

Common Standard Exceptions:


std::exception: Base class for all standard exceptions.

std::runtime_error: Indicates errors that can only be detected during runtime.

std::logic_error: Indicates errors in program logic (e.g., invalid arguments).

std::out_of_range: Indicates an out-of-range access attempt.

std::invalid_argument: Indicates an invalid argument passed to a function.

Custom exception classes:


Defining a custom exception:

13
Object Oriented Programming Cheat Sheet

Throwing a custom exception:

Best practices:

Always catch by reference: catch exception by reference to avoid slicing.

Use specific exceptions: catch specific exceptions before more general ones.

Avoid using exceptions for control flow: use exceptions for error handling only,
not as a mechanism for controlling program flow.

Example:

14
Object Oriented Programming Cheat Sheet

Templates:
Templates are a powerful feature that allows you to write generic and reusable code. They
enable you to define functions and classes that can operate with any data type without
knowing the exact type in advance. Templates help you achieve type independence and
flexibility in your code.

Types of templates:

Function template:
Function templates allow you to create functions that work with any data type. You define
a template with a placeholder for the type and then use it for various types.

Class templates:
Class templates allow you to create
classes that operate with any data type.
You define a template with a
placeholder for the type and then use it
to create instances with different
types.

15
Object Oriented Programming Cheat Sheet

Template specialization:

Full specialization:
Full specialization provides a complete and specific implementation of a template for a
particular type or set of types.

16
Object Oriented Programming Cheat Sheet

Partial specialization:
Partial specialization allows you to define a template that is specialized for a subset
of template parameters while leaving the rest generic. This is useful when you want
to specialize the template based on some but not all template parameters.

Structures:
A structure (often abbreviated as struct) is a user-defined data type that groups
together variables (members) of different types under a single name. Structures provide a

17
Object Oriented Programming Cheat Sheet

way to encapsulate related data items, making it easier to manage and organize complex
data.

Syntax:

Key features:

Member variables: structures can contain multiple members of different types


including other structures, types, pointers, function.

Accessing member: members of struct can be accessed using a dot(.).

Initialization: structures can be initialized using an initializer list.

Arrays of structures:

Structures and functions:


Structures can be passed to functions as parameters.

18
Object Oriented Programming Cheat Sheet

Difference between structures and class?


Aspects Structures Class
Default access Members are public by Members are private by
default default
Default inheritance Inheritance is public by Inheritance is private by
default default
Use cases Used for simple data Used for complex objects
aggregation without much with encapsulation and
behavior. behavior.
Encapsulation Less emphasis on Focuses on encapsulation;
encapsulation; default access default access is private.
is public.
Compatibility and Historically used in C for Used more extensively in C++
conventions data aggregation. In C++, for object-oriented
struct has similar capabilities
programming, including
to class but with default inheritance, polymorphism,
public access. Typically used and encapsulation. Preferred
in simpler or POD (Plain Old for defining objects with
Data) structures. significant behavior or
requiring data hiding.
With structs, the inherited members maintain their public accessibility and lack the
encapsulation features of classes. This distinction alters the way we perceive and
implement inheritance with structs.

When to use structures over classes?


Value vs reference types: Structs are value types, while classes are
reference types. This means that when you
pass a struct to a method, a copy of the
entire data is passed. In contrast, when you
pass a class to a method, a reference to the
object is passed. This distinction can impact
performance, particularly for small,
lightweight objects where copying the value
might be more efficient than the overhead

19
Object Oriented Programming Cheat Sheet

associated with passing a reference.


Memory allocation: Structs are allocated on the stack, while
classes are allocated on the heap. Stack
allocation is typically faster and more
efficient, especially for small and
frequently-used objects, compared to heap
allocation, which involves additional
overhead and potential fragmentation.
Immutability: sturctures are more suitable to
representing immutable data,as they are
passed by value rather then reference.

Enum:
An enum (short for "enumeration") in C++ is a user-defined data type comprising a set of
named integral constants. It is utilized to define variables that can take on a specific,
predefined set of values, thereby enhancing the readability and maintainability of your
code.

Default Values: Enumerators start at 0 by default, with each subsequent enumerator


incremented by 1.

Scoped Enums: enum class provides better type safety and avoids name conflicts.

Advantages: Enums enhance code readability, maintainability, and type safety.


Enums are especially useful when a variable is limited to a small, predefined set of possible
values, such as states, options, or configurations.

20
Object Oriented Programming Cheat Sheet

Union:
A union in C++ is a user-defined data type that enables you to store different data types in
the same memory location. Unlike a structure, which allocates separate memory for each
member, a union uses a single memory block that is shared among all its members.
Consequently, a union can hold only one of its non-static data members at any given time.

Key Features of Unions:

Memory Efficiency: Unions are more memory-efficient than structures because they
allocate space only for the largest member, sharing a single memory block among all
members.

Size of Union: The size of a union is determined by the size of its largest member. This
ensures that the union can accommodate the largest data type it holds.

Overwriting Data: When you assign a value to one member of a union, it overwrites the
data of other members. Accessing the value of an overwritten member may result in
undefined behavior.

21
Object Oriented Programming Cheat Sheet

Use Cases: Unions are valuable for working with different data types efficiently in
memory-constrained environments, such as low-level programming or handling varied data
types in protocols.

What is Object Oriented Programming?


Object-Oriented Programming(OOPs) is a type of programming that is based on objects
rather than just functions and procedures. Individual objects are grouped into classes.
OOPs implements real-world entities like inheritance, polymorphism, hiding, etc into
programming. It also allows binding data and code together.

Why use OOPs?


• OOPs allows clarity in programming thereby allowing simplicity in solving
complex problems

22
Object Oriented Programming Cheat Sheet

• Code can be reused through inheritance thereby reducing redundancy


• Data and code are bound together by encapsulation
• OOPs allows data hiding, therefore, private data is kept confidential
• Problems can be divided into different parts making it simple to solve
• The concept of polymorphism gives flexibility to the program by allowing the
entities to have multiple forms

Can you call the base class method without creating an


instance?
Yes, you can call the base class without instantiating it if:

• It is a static method
• The base class is inherited by some other subclass

23

You might also like