cpp unit 3
cpp unit 3
INHERITANCE
Definition:
Inheritance is a fundamental concept in object-oriented programming
(OOP) where a new class (derived class) is created by extending an
existing class (base class).
It allows the derived class to inherit properties and behaviors (member
variables and member functions) from the base class, promoting code
reuse and hierarchical organization of classes
Concept of Inheritance
Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from
a single base class.
This creates a hierarchical structure where multiple classes share
common properties and behaviors.
Example:
Multilevel Inheritance:
In multilevel inheritance, a derived class inherits properties and
behaviors from a base class, and then another class derives from
that derived class.
This creates a chain of inheritance.
Example:
Hybrid Inheritance:
Hybrid inheritance combines different types of inheritance, such as
single, multiple, hierarchical, and multilevel inheritance.
This allows for more complex class relationships.
Example:
Dynamic Memory Allocation:
The new operator allocates memory for a single object or an
array of objects of a specified type.
It returns a pointer to the allocated memory.
Syntax:
To allocate memory for a single object, use new followed by the
data type:
Initialization:
The new operator also allows for initialization of allocated
memory using parentheses:
Memory Deallocation:
Memory allocated using the new operator must be explicitly
deallocated using the delete operator to avoid memory leaks.
For single objects:
Error Handling:
It's essential to handle the scenario where memory allocation
fails.If memory allocation fails, the new operator throws a
std::bad_alloc exception.
To prevent the program from terminating unexpectedly, you can
use exception handling or check for nullptr after memory
allocation.