Write C++ program to demonstrate example of hierarchical inheritance to get square and cube of a number.
#include <iostream> / using namespace std; / class N { protected: int n; public: N(int x) : n(x) {} }; / class S :
public N { public: S(int x) : N(x) {} int sq() { return n*n; } }; / class C : public N { public: C(int x) : N(x) {} int cu() {
return n*n*n; } }; / int main() / { S s(5); C c(3); cout << s.sq() << endl << c.cu() << endl; }
this pointer : Implicit pointer to the current object. Used to access object's members, return *this for chaining.
Ex- class A {public: / int x; / A(int v) : x(v) {} / A& func() { x *= 2; return *this; }};
Access specifiers : public: Accessible from anywhere. private: Accessible only within the class. protected:
Accessible within the class and derived classes. Ex- class A / {public: int x; / private: int y; / protected: int z;};
Dynamic memory allocation : new operator: Allocates memory for an object, returns a pointer. delete
operator: Deallocates memory. Ex- int* p = new int(10); / *p = 20; / cout << *p; / delete p;
Creating a Custom Exception Class in C+ : #include <iostream> / #include <exception>/class MyException :
public std::exception {/public:/ const char* what() const noexcept override {/ return "This is my custom
exception"/ }/};/int main() {/try {/ throw MyException();/ } catch (const MyException& e) {/ std::cerr <<
e.what() << std::endl/ }/ return 0; /}Custom Exception Class: MyException inherits from std::exception.what()
function: Overridden to provide a custom error message.Throwing and Catching: The try-catch block
demonstrates throwing and catching the custom exception.
Functionality of what() Returns a const char* representing the error message. Provides a standard way for
exception objects to describe themselves. Used by std::cerr in the catch block to print the error message.
Stack Unwinding in C++ Stack unwinding is the process of deallocating function frames from the stack when an
exception is thrown and not caught immediately. It involves: Destructor Calls: Destructors of objects created in
the current function are called. Function Return: The function returns without executing further code.Stack
Frame Removal: The function's stack frame is removed. Exception Propagation: The exception is passed to the
calling function. #include <iostream> /void func3() {/std::cout << "func3\n"; /throw std::runtime_error("Error
in func3"); /}void func2() { / std::cout << "func2\n"; /func3(); // Exception thrown here /} /void func1() { /
std::cout << /"func1\n";func2(); /} /int main() { /try { /func1(); / } catch (const std::runtime_error& e) {
/std::cerr << e.what() << std::endl;   / } / return 0; /}   Output: func1 /func2/func3 /Error in func3 /The
output shows that func3, func2, and func1 are executed until the exception is thrown in func3. Then, stack
unwinding occurs, and the exception is caught in main.
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to design and develop                          Abstract classes are a fundamental concept in object-oriented programming (OOP) that provide a blueprint for
software. These objects represent real-world entities and have attributes (data) and behaviors (methods/functions).            other classes. They cannot be instantiated directly, meaning you can't create objects of their type. Instead, they
OOP promotes code reusability, modularity, and the organization of software into manageable, maintainable, and                 serve as a base for derived or subclass classes. Key Characteristics: Abstract Methods: These are methods declared
scalable components. Basic Concepts of OOP: OOP is built on four fundamental concepts, often referred to as the                without a body. Subclasses must implement these methods to provide specific behavior. Concrete Methods: These
"four pillars" of OOP: Encapsulation: Encapsulation is the bundling of data (attributes) and methods (functions) that          are methods with a defined implementation that can be inherited by subclasses. Inheritance: Abstract classes can
operate on the data into a single unit or class. It restricts direct access to some of the object's components, which is       be inherited by other classes, providing a common structure and behavior.
a means of preventing accidental interference and misuse of the data. Abstraction: Abstraction is the concept of               Advantages of Abstract Classes: Encapsulation and Abstraction: Abstract classes promote good programming
hiding the complex implementation details and showing only the essential features of an object. It allows the                  practices by encapsulating common functionality and abstracting away implementation details. Code Reusability:
programmer to focus on the interface of the object rather than its implementation. Inheritance: Inheritance is a               By defining common methods in an abstract class, you can avoid code duplication in subclasses. Polymorphism:
mechanism by which a new class (derived class) can inherit properties and behaviors (attributes and methods) from              Abstract classes enable polymorphism, allowing objects of different subclasses to be treated as if they were of the
an existing class (base class). This promotes code reusability and establishes a relationship between different                same type. Code Organization: Abstract classes help organize code into a hierarchical structure, making it easier to
classes. Polymorphism: Polymorphism is the ability of a single function or method to behave differently based on               understand and maintain. Design Patterns: Many design patterns, such as the Template Method and Factory
the object that it is acting upon. It allows for the use of a single interface to represent different underlying forms         patterns, rely on abstract classes to provide a flexible framework.
(data types).
                                                                                                                               Exception is an event that occurs during the execution of a program that disrupts the normal flow of the program's
A class in C++ (and other object-oriented programming languages) is a blueprint or template for creating objects. It           instructions. It's essentially an error or abnormal condition that arises unexpectedly. Examples of exceptions:
defines a data structure by specifying the data (attributes or properties) and the functions (methods or behaviors)            Trying to divide a number by zero (ArithmeticException). Accessing an array element that doesn't exist
that can operate on that data. In simpler terms, a class defines what an object will look like and what it can do, but         (ArrayIndexOutOfBoundsException). Trying to open a file that doesn't exist (FileNotFoundException)
it doesn't create the object itself.                                                                                           Exception handling is a mechanism to handle these exceptions gracefully, preventing program crashes and ensuring
An object is an instance of a class. When you create an object, you are creating an actual entity that has the                 that the program continues to execute even when errors occur. It involves: Catching exceptions: Using try and catch
structure and behavior defined by the class. Objects can hold specific values for the attributes defined by the class          blocks to intercept exceptions. Handling exceptions: Providing code within the catch block to handle the exception
and can perform actions using the methods defined in the class. In simple terms, if a class is a blueprint, then an            and take appropriate actions. Throwing exceptions: Using the throw keyword to explicitly raise an exception. Finally
object is a house built from that blueprint. Each object can have different values for its attributes, but all objects of      block: Code that always executes, regardless of whether an exception is thrown or caught. Benefits of exception
the same class will have the same structure and behaviors. Key Points: Class: A blueprint for objects; defines                 handling: Improves program reliability and robustness. Prevents unexpected program termination. Provides better
attributes and methods. Object: An instance of a class; a specific entity with values for the attributes defined by the        error reporting and recovery mechanisms. Enhances code maintainability.
class and the ability to perform the class's methods.
                                                                                                                               Overloading occurs when multiple methods in the same class have the same name but different parameters. The
A constructor in C++ is a special member function of a class that is automatically called when an object of the class          compiler determines which method to call based on the arguments passed to it. Key points: Occurs within the
is created. Its primary purpose is to initialize the object's attributes (i.e., setting initial values for the data members)   same class. Different parameter lists. Compile-time polymorphism. void print(int x) { ... } / void print(double x) { ... }
and to allocate resources if necessary. Key Characteristics of Constructors: Same Name as the Class: The                       Overriding occurs when a subclass provides a specific implementation for a method that is already defined in its
constructor's name must be exactly the same as the class name. No Return Type: Constructors do not have a return               parent class. This allows the subclass to modify the behavior of the inherited method. Key points: Occurs in
type, not even void. Automatically Called: It is invoked automatically when an object is created. Can Be                       different classes with an inheritance relationship. Same method signature (name and parameters). Run-time
Overloaded: You can define multiple constructors with different parameters.                                                    polymorphism. class Animal { void speak() { ... }} / class Dog : public Animal / { void speak() { std::cout << "Woof!" <<
                                                                                                                               std::endl; }}
A destructor in C++ is a special member function of a class that is automatically called when an object goes out of
scope or is explicitly deleted. Its primary purpose is to perform cleanup tasks, such as releasing resources that the          Binding refers to the process of linking a function call with its actual code. This can happen at compile time or
object may have acquired during its lifetime (e.g., memory, file handles, etc.). Key Characteristics of Destructors:           runtime. Early Binding : Determined at compile time. The compiler knows exactly which function to call based on
Same Name as the Class but Prefixed with a Tilde (~): The destructor's name is the same as the class name, but it              the static type of the object. Typically used with overloaded methods. Offers better performance due to direct
starts with a ~ symbol. No Return Type: Destructors do not have a return type, not even void. No Parameters:                   function calls.
Destructors cannot be overloaded and do not take any arguments. Automatically Called: It is automatically invoked              Late Binding: Determined at runtime. The specific method to be called is decided based on the actual type of the
when an object is destroyed.                                                                                                   object at runtime. Used with overridden methods and virtual functions. Provides flexibility but can be slightly
                                                                                                                               slower due to the runtime lookup. In essence: Early binding: The compiler decides which method to call based on
A virtual function in C++ is a member function in a base class that you expect to be overridden in derived classes.            the declared type of the object. Late binding: The runtime environment decides which method to call based on the
When a function is declared as virtual, C++ determines which function to call at runtime based on the type of the              actual type of the object.
object pointed to, rather than the type of the pointer or reference. This enables polymorphism, allowing a function
to behave differently depending on the derived class instance that is being used. Key Characteristics of Virtual               Keywords are reserved words in programming languages that have predefined meanings and cannot be used as
Functions: Declared with the virtual Keyword: A virtual function is declared using the virtual keyword in the base             identifiers (variable, function, or class names). In object-oriented programming (OOP), certain keywords are crucial
class. Supports Polymorphism: Virtual functions allow derived classes to override the base class function and                  for defining and manipulating objects, classes, and their relationships. Core OOP Keywords: class: Defines a new
provide specific implementations. Dynamic Binding: Unlike regular functions (which are statically bound at compile-            class, which is a blueprint for creating objects. object: An instance of a class. new: Creates an object of a class. this:
time), virtual functions are dynamically bound at runtime, which means the actual function that gets executed is               A reference to the current object within a method. super: Refers to the parent class object. extends: Used for
determined based on the type of the object being pointed to.                                                                   inheritance, specifying a base class. implements: Used to implement an interface. Other Important Keywords:
                                                                                                                               public: Access modifier allowing elements to be accessed from anywhere. private: Access modifier restricting
A friend function in C++ is a function that is not a member of a class but still has access to the class's private and         access to within the class. protected: Access modifier allowing access within the class and its subclasses. static:
protected members. By default, private and protected members of a class cannot be accessed outside of the class.               Keyword for class-level variables and methods. final: Prevents a class from being inherited, a method from being
However, by declaring a function as a friend, you allow it to access these members directly. Key Points: 1. A friend           overridden, or a variable from being modified. abstract: Defines an abstract class or method. interface: Defines an
function is declared by using the friend keyword within the class whose members it needs to access. 2. Friend                  interface. try, catch, finally: Keywords for exception handling.
functions can be useful for certain operations, such as overloading operators that need to access private members
of a class.                                                                                                                    Operator Overloading: Unary Minus (-): Operator overloading in C++ allows you to redefine the behavior of built-in
A pure virtual function in C++ is a function that is declared in a base class but has no definition within that class.         operators for user-defined data types. In this case, we'll overload the unary minus (-) operator for a custom Number
Instead, it must be overridden by derived classes. A class that contains at least one pure virtual function is                 class. code :- #include <iostream> / using namespace std; / class Number / {public: / int value; / Number(int val) :
considered an abstract class and cannot be instantiated on its own. The purpose of a pure virtual function is to               value(val) {} / Number operator-() / { return Number(-value); } / void display() / {cout << value << endl;}}; / int
provide a common interface for all derived classes, while leaving the implementation to the derived classes. Key               main() / { Number num(10); / cout << "Original value: "; / num.display(); / Number neg_num = -num; / cout <<
Points: 1.A pure virtual function is declared by assigning 0 to the function declaration. 2.Any class inheriting from a        "Negated value: "; / neg_num.display(); / return 0;} o/p: Original value: 10, Negated value: -10
class with a pure virtual function must provide an implementation for that function, or it will also be abstract.
                                                                                                                               Pure Virtual Function: A pure virtual function is a virtual function declared in a base class without an
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different                    implementation. It's declared by assigning 0 to the function body. A class containing at least one pure virtual
types to be treated as if they were of the same type. It essentially means "many forms," and it enables code to be             function is called an abstract class. Overriding: Overriding is the process of redefining a virtual function in a derived
written more flexibly and efficiently. There are two main types of polymorphism:                                               class. The function in the derived class must have the same signature as the base class function. Program :-
Compile-Time Polymorphism: Determined at compile time: The compiler decides which function to call based on                    #include <iostream> / using namespace std; / class Base / {public: / virtual void print() = 0; }; / class Derived :
the static type of the object (the type declared in the code). Achieved through: Method overloading.                           public Base / { public: / void print() override / { cout << "BEU Patna" << endl; } } ; / int main() / { Derived obj; /
Key characteristics: Multiple methods with the same name but different parameters. The compiler selects the                    obj.print(); / return 0; } Output: BEU Patna
appropriate method based on the argument types. Faster execution as the decision is made at compile time.
Run-Time Polymorphism : Determined at run time: The actual method to be called is decided based on the                         Why Converting Base-Class Pointer to Derived-Class Pointer is Dangerous :- Understanding the Issue: In C++, a
dynamic type of the object (the actual type of the object at runtime). Achieved through: Method overriding and                 base class pointer can point to a derived class object, but the reverse is not safe. This is because: Size Difference:
virtual functions. Key characteristics: A base class method is overridden in a derived class. The method to be called          Derived classes typically contain more data members than their base class. Converting a base class pointer to a
is determined at runtime based on the object's actual type. Slower execution compared to compile-time                          derived class pointer assumes that the memory layout of the derived class is identical to the base class, which is
polymorphism due to the runtime lookup.            Differences :                                                               incorrect. Data Loss: If you cast a base class pointer to a derived class pointer and access members specific to the
Feature                         Compile-Time Polymorphism                                   Run-Time Polymorphism              derived class, you might access memory locations that are not part of the base class object, leading to undefined
Timing                          Compile time                                Run time                                           behavior or data corruption. Type Safety: The compiler ensures type safety by preventing implicit conversions from
Mechanism                       Method overloading                          Method overriding                                  base class pointers to derived class pointers. This helps catch potential errors at compile time.
Binding                         Static binding                              Dynamic binding
Speed                           Faster                                      Slower                                             which accepts the user's first and last name and print them in reverse order with space between them :- #include
Flexibility                     Less flexible                               More flexible                                      / <iostream> / #include <string> / using namespace std; / int main() / { string firstName, lastName; / cout <<
                                                                                                                               "Enter your first name: "; / cin >> firstName; / cout << "Enter your last name: "; / cin >> lastName; / cout <<
Abstract Class & Interface Diff :- Abstract Class: Can have both abstract and concrete methods. Can have instance              lastName << " " << firstName << endl; / return 0; }
variables. Supports single inheritance. Provides a partial implementation. Used for code reusability and defining a            Write a program in C++ to read text file and display count of character in file:- #include <iostream> /
common template for related classes. Interface: Contains only abstract methods . Can have default and static                   #include<fstream> / using namespace std; / int main() / { ifstream file("text.txt"); / int count = 0; / char ch; / while
methods. Cannot have instance variables. Supports multiple inheritance. Defines a contract that classes must                   (file.get(ch)) count++; / cout << count << endl; / return 0; }
adhere to. Used for achieving complete abstraction and defining a common protocol.                                             Constructor and Area of a Circle : Constructor is a special member function of a class that is automatically invoked
Feature                       Abstract Class                                Interface                                          when an object of the class is created. It is used to initialize the data members of an object. Code :
Methods                       Abstract and concrete                         Only abstract, default and static                  #include<iostream> / using namespace std; / class Circle / { public: / double radius; / Circle(double r) : radius(r) {} /
Variables                     Instance variables                            Static final variables                             double area() { return 3.14159 * radius * radius; }}; / int main() / {Circle c(5); / cout << c.area() << endl; / return 0;}
Inheritance                   Single inheritance                            Multiple inheritance                               Write a C++ program to find the sum of the series 1+3+5+.......+n. :- #include <iostream> / using namespace std; /
Implementation                Partial                                       No implementation                                  int main() / { int n, sum = 0; / cout << "Enter the value of n: "; / cin >> n; / sum = (n * n); / cout << "The sum of
Purpose                       Code reusability, common template             Contract, complete abstraction                     the series 1 + 3 + 5 + ... + " << n << " is: " << sum << endl; / return 0; }
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes                C++ program to define a class string and use overloaded to operator compare two strings: #include<iostream> /
(called subclasses or derived classes) by inheriting properties and methods from existing classes (called superclasses         #include <cstring> / using namespace std; / class String / { public: / char *str; / String(const char *s) { str = new
or base classes). This promotes code reusability and helps organize code into hierarchical relationships. Key                  char[strlen(s) + 1]; strcpy(str, s); } / bool operator==(const String &s) const { return strcmp(str, s.str) == 0; }}; / int
Concepts: Base Class: The parent class from which properties and methods are inherited. Derived Class: The child               main() / { String s1("hello"), s2("world"); / if (s1 == s2) cout << "Equal" << endl; / else cout << "Not equal" << endl; /
class that inherits from the base class. Is-a Relationship: A derived class is considered a specialized version of its         return 0;}
base class. For example, a "Dog" is a type of "Animal." Benefits of Inheritance: Code Reusability: Avoids redundant            Program that uses a function template called max to determine the largest of three arguments:
code by sharing common properties and methods among related classes. Hierarchical Classification: Organizes                    #include<iostream> / using namespace std; / template <typename T> / T max(T a, T b, T c) / {return (a > b) ? (a > c ?
classes into a clear hierarchy, improving code readability and maintainability. Polymorphism: Enables objects of               a : c) : (b > c ? b : c);} / int main() / {cout << max(3, 7, 5) << endl; / cout << max('z', 'a', 'm') << endl; / cout <<
different types to be treated as if they were of the same type.                                                                max(3.14, 2.71, 4.15) << endl; / return 0; }