Object Oriented Design and Programming Unit-03

sivakumarmcs 48 views 58 slides May 29, 2024
Slide 1
Slide 1 of 58
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58

About This Presentation

Object Oriented Design and Programming,
Unit-03,
SRM University,
II Semester,
Regulation 2021


Slide Content

21CSC101T OBJECT ORIENTED DESIGN AND PROGRAMMING Dr.M.Sivakumar AP/NWC SRMIST

Course Outcomes (CO ) At the end of this course, learners will be able to: CO-1: Create programs using object-oriented approach and design methodologies CO-2: Construct programs using method overloading and operator overloading CO-3: Create programs using inline, friend and virtual functions, construct programs using standard templates CO-4: Construct programs using exceptional handling and collections CO-5: Create Models of the system using UML Diagrams

Unit-3 - Inheritance Inheritance – Types -Single and Multiple Inheritance - Multilevel Inheritance - Hierarchical Inheritance - Hybrid Inheritance - Advanced Functions - Inline, Friend- Virtual - Pure Virtual function - Abstract class – UML State Chart Diagram - UML Activity Diagram

Inheritance the mechanism by which a class can inherit properties (fields) and behaviors (methods) from another class. enables code reuse and promotes modularity and extensibility in software development establishes an "is-a" relationship between classes, where a subclass (or derived class) inherits characteristics from a superclass (or base class). The subclass inherits all non-private members (methods and fields) of the superclass , allowing it to reuse the code defined in the superclass .

Inheritance Examples

Inheritance Examples

Inheritance Examples

Inheritance Examples

Inheritance Syntax: class DerivedClass : accessSpecifier BaseClass { // Derived class members and methods }; DerivedClass the name of the derived class. accessSpecifier specifies the access level for the inherited members. It can be public, protected, or private. If not explicitly specified, it defaults to private. BaseClass the name of the base class being inherited from.

Inheritance Public Public members of the base class remain public in the derived class. They are accessible from outside the class hierarchy. Protected Public members of the base class become protected in the derived class. They are accessible within the derived class and its subclasses but not from outside. Private Public members of the base class become private in the derived class. They are not accessible from the derived class or outside.

Inheritance class Base { public: int publicMember ; protected: int protectedMember ; private: int privateMember ; }; class DerivedPublic : public Base { // publicMember is accessible // protectedMember is accessible // privateMember is not accessible }; class DerivedProtected : protected Base { // publicMember is accessible // protectedMember is accessible // privateMember is not accessible }; class DerivedPrivate : private Base { // publicMember is accessible // protectedMember is accessible // privateMember is not accessible };

Types

Types Single Inheritance Multiple Inheritance Multilevel Inheritance Hierarchical Inheritance Hybrid Inheritance

Single Inheritance Single inheritance refers to the inheritance mechanism where a derived class inherits from only one base class.

Single Inheritance Syntax class BaseClass { // Base class members and methods }; class DerivedClass : accessSpecifier BaseClass { // Derived class members and methods };

Single Inheritance Example #include < iostream > using namespace std; // Base class class Animal { public: void eat() { cout << "Animal is eating.\n"; } }; // Derived class inheriting from Animal class Dog : public Animal { public: void bark() { cout << "Dog is barking.\n"; } }; int main() { Dog myDog ; myDog.eat(); // Output: Animal is eating. myDog.bark (); // Output: Dog is barking. return 0; } Animal is the base class with a method eat() . Dog is the derived class inheriting from Animal . Dog adds its own method bark() . main() function demonstrates the use of the derived class Dog .

Multiple Inheritance Multiple inheritance is a feature in object-oriented programming where a class can inherit attributes and methods from more than one base class.

Multiple Inheritance Syntax class BaseClass1 { // Base class 1 members and methods }; class BaseClass2 { // Base class 2 members and methods }; class DerivedClass : accessSpecifier BaseClass1, accessSpecifier BaseClass2 { // Derived class members and methods };

Multiple Inheritance Example #include < iostream > using namespace std; // Base class representing a vehicle's movement capabilities class Movement { public: void move() { cout << "Vehicle is moving\n"; } }; // Base class representing a vehicle's fuel-related functionalities class Fuel { public: void refillFuel () { cout << "Refilling fuel\n"; } }; // Derived class representing a car, which inherits from both Movement and Fuel class Car : public Movement, public Fuel { public: void honk() { cout << "Car is honking\n"; } }; int main() { Car myCar ; myCar.move (); // Accessing method from Movement myCar.refillFuel (); // Accessing method from Fuel myCar.honk (); // Accessing method from Car return 0; }

Multilevel Inheritance Multilevel inheritance is a feature in object-oriented programming where a class serves as a base class for another class, and that derived class, in turn, serves as the base class for yet another class.

Multilevel Inheritance Syntax class BaseClass { // Base class members and methods }; class DerivedClass1 : accessSpecifier BaseClass { // Derived class 1 members and methods }; class DerivedClass2 : accessSpecifier DerivedClass1 { // Derived class 2 members and methods };

Multilevel Sample Program #include < iostream > using namespace std; // Base class class Animal { public: void eat() { cout << "Animal is eating.\n"; } }; // Derived class inheriting from Animal class Dog : public Animal { public: void bark() { cout << "Dog is barking.\n"; } }; // Another derived class inheriting from Dog class Bulldog : public Dog { public: void guard() { cout << "Bulldog is guarding.\n"; } }; int main() { Bulldog myBulldog ; myBulldog.eat(); // Accessing method from Animal myBulldog.bark (); // Accessing method from Dog myBulldog.guard (); // Accessing method from Bulldog return 0; }

Hierarchical Inheritance Hierarchical inheritance is a type of inheritance in C++ where more than one derived class inherits from a single base class. In hierarchical inheritance, the derived classes share common features inherited from the same base class, but they may have their own unique attributes or behaviors.

Hierarchical Inheritance Syntax class BaseClass { // Base class members and methods }; class DerivedClass1 : accessSpecifier BaseClass { // Derived class 1 members and methods }; class DerivedClass2 : accessSpecifier BaseClass { // Derived class 2 members and methods };

Hierarchical Inheritance Sample Program #include < iostream > using namespace std; // Base class class Shape { public: void draw() { cout << "Drawing a shape\n"; } }; // Derived class 1 inheriting from Shape class Circle : public Shape { public: void drawCircle () { cout << "Drawing a circle\n"; } }; // Derived class 2 inheriting from Shape class Rectangle : public Shape { public: void drawRectangle () { cout << "Drawing a rectangle\n"; } }; int main() { Circle circle ; circle.draw (); // Accessing method from Shape circle.drawCircle (); // Accessing method from Circle Rectangle rectangle ; rectangle.draw (); // Accessing method from Shape rectangle.drawRectangle (); // Accessing method from Rectangle return 0; }

Hybrid Inheritance Hybrid inheritance is a combination of multiple types of inheritance, typically mixing single inheritance, multiple inheritance, and/or multilevel inheritance. It forms a complex inheritance hierarchy. This type of inheritance can lead to the diamond problem, which arises when two base classes of a class have a common base class themselves.

Hybrid Inheritance Syntax class BaseClass1 { // Base class 1 members and methods }; class BaseClass2 { // Base class 2 members and methods }; class DerivedClass1 : accessSpecifier BaseClass1 { // Derived class 1 members and methods }; class DerivedClass2 : accessSpecifier BaseClass1, accessSpecifier BaseClass2 { // Derived class 2 members and methods }; class DerivedClass3 : accessSpecifier DerivedClass1, accessSpecifier DerivedClass2 { // Derived class 3 members and methods };

#include < iostream > using namespace std; // Base class 1 class Animal { public: void eat() { cout << "Animal is eating.\n"; } }; // Base class 2 class Machine { public: void work() { cout << "Machine is working.\n"; } }; // Derived class 1 inheriting from Animal (Single Inheritance) class Dog : public Animal { public: void bark() { cout << "Dog is barking.\n"; } }; // Derived class 2 inheriting from Machine (Single Inheritance) class Car : public Machine { public: void drive() { cout << "Car is driving.\n"; } }; // Derived class 3 inheriting from both Dog and Car (Multiple Inheritance) class RobotDogCar : public Dog, public Car { public: void move() { cout << " RobotDogCar is moving.\n"; } }; // Derived class inheriting from RobotDogCar (Multilevel Inheritance) class SuperRobot : public RobotDogCar { public: void fly() { cout << " SuperRobot is flying.\n"; } };

int main() { SuperRobot mySuperRobot ; mySuperRobot.eat(); // Accessing method from Animal (via Dog) mySuperRobot.work (); // Accessing method from Machine (via Car) mySuperRobot.bark (); // Accessing method from Dog mySuperRobot.drive (); // Accessing method from Car mySuperRobot.move (); // Accessing method from RobotDogCar mySuperRobot.fly(); // Accessing method from SuperRobot return 0; }

Constructor in Inheritance Constructors in inheritance play a crucial role in initializing base class and derived class objects. In C++, when you create a derived class object, the constructors of both the base class and derived class are called in a certain order. The base class constructor is called before the derived class constructor.

Constructor in Inheritance Base Class Constructor When a derived class object is created, the constructor of the base class is invoked first to initialize the base class part of the object. This happens automatically before the derived class constructor body executes. Derived Class Constructor : After the base class constructor completes its execution, the derived class constructor is invoked. It can initialize the derived class members and perform additional initialization tasks specific to the derived class.

Constructor in Inheritance Example #include < iostream > using namespace std; // Base class class Base { public: Base() { cout << "Base class constructor\n"; } }; // Derived class class Derived : public Base { public: Derived() { cout << "Derived class constructor\n"; } }; int main() { Derived d; // Creating an object of the derived class return 0; } When an object of the Derived class is created in the main() function, the constructor of the Base class is called first, followed by the constructor of the Derived class.

Advanced Functions Inline Friend Virtual - Pure Virtual function

Inline Functions In C++, the inline keyword is used to suggest the compiler to perform inline expansion of a function. When a function is declared as inline, the compiler replaces the function call with the actual function code during the compilation process, thereby avoiding the overhead of function call and improving performance. Syntax: inline returnType functionName (parameters) { // Function body }

Inline Functions Example #include < iostream > using namespace std; // Inline function definition inline int add( int a, int b) { return a + b; } int main() { int result = add(3, 5); // Function call cout << "Result: " << result << endl ; return 0; }

Inline Functions Features Inline functions are typically used for small functions. They are often defined in header files to allow for inclusion in multiple source files without violating the One Definition Rule. Using inline for large or complex functions may result in larger executable size and may not yield performance benefits. Functions defined inside class definitions are implicitly inline.

Friend Functions In C++, a friend function is a function that is not a member of a class but has access to the private and protected members of the class. It is declared within the class using the friend keyword. Friend functions are useful when you need to allow an external function to access private or protected data of a class without making that function a member of the class.

Friend Functions Syntax class ClassName { private: // Private members public: // Public members // Declaration of friend function friend returnType functionName (parameters); }; // Definition of the friend function returnType functionName (parameters) { // Function body }

Features of friend functions Access to Private and Protected Members Non-Member Functions Declaration Inside Class Symmetric Relationship Granular Access Control No Inheritance Implications Friendship is Not Transitive Use with Operator Overloading

Friend Function example #include < iostream > using namespace std; // Forward declaration of class Rectangle class Rectangle; // Class Square class Square { private: int side; public: Square( int s) : side(s) {} // Declaration of friend function friend void compareArea (const Square& sq, const Rectangle& rect ); }; // Class Rectangle class Rectangle { private: int length; int width; public: Rectangle( int l, int w) : length(l), width(w) {} // Declaration of friend function friend void compareArea (const Square& sq, const Rectangle& rect ); }; // Definition of friend function void compareArea (const Square& sq, const Rectangle& rect ) { int areaSq = sq.side * sq.side ; int areaRect = rect.length * rect.width ; if ( areaSq > areaRect ) { cout << "Area of square is greater than area of rectangle\n"; } else if ( areaSq < areaRect ) { cout << "Area of rectangle is greater than area of square\n"; } else { cout << "Area of square is equal to area of rectangle\n"; } } int main() { Square square (5); Rectangle rectangle (4, 6); // Call to the friend function compareArea (square, rectangle); return 0; }

Virtual function In C++, a virtual function is a member function declared within a base class that can be overridden by derived classes. When a virtual function is called through a base class pointer or reference pointing to a derived class object, the appropriate version of the function is invoked based on the actual object type.

Virtual function Declaration : To declare a function as virtual, use the virtual keyword in the base class. Override : Derived classes can override the virtual function by providing their own implementation of the function with the same signature. Dynamic Binding : The appropriate version of the virtual function is determined at runtime based on the type of the object being referred to, not the type of the pointer or reference.

Virtual function Example #include < iostream > using namespace std ; class Shape {     public:     virtual void area ()     {         cout << "Area of shape" << endl ;     } }; class Rectangle : public Shape {     public:     void area ()     {             cout << "Area of Rectangle" << endl ;     } }; class Circle : public Shape { public:     void area ()     {             cout << "Area of Circle" << endl ;     }     }; int main () {     Rectangle rect ;     Circle cir;     Shape * sp;         sp = & rect ;     sp-> area ();     sp = &cir;     sp-> area ();     return 0; }

Pure Virtual function A pure virtual function is a virtual function that has no implementation in the base class and is meant to be overridden by derived classes. It serves as a placeholder for the derived classes to provide their own implementations. A class containing at least one pure virtual function becomes an abstract base class, and instances of abstract base classes cannot be created. Derived classes must provide an implementation for all pure virtual functions to be considered concrete classes.

Virtual function Example #include < iostream > using namespace std ; class Shape {     public:     virtual void area () =0; }; class Rectangle : public Shape {     public:     void area () override     {             cout << "Area of Rectangle" << endl ;     } }; class Circle : public Shape { public:     void area () override     {             cout << "Area of Circle" << endl ;     }     }; int main () {     Rectangle rect ;     Circle cir;     Shape * sp;         sp = & rect ;     sp-> area ();     sp = &cir;     sp-> area ();     return 0; }

Abstract class In C++, an abstract class is a class that cannot be instantiated on its own. It serves as a blueprint for other classes, defining a common interface through which derived classes can inherit functionality. A class containing at least one pure virtual function becomes an abstract base class, and instances of abstract base classes cannot be created.

UML State Chart Diagram Depicts the various states that an object can be in during its lifetime and the transitions between those states Used for modeling the dynamic behavior of a system or component Used for showing how it responds to events and changes over time

Components of a UML State Chart Diagram States : Represents the various conditions or situations in which an object or system can exist. States are typically depicted as rounded rectangles with the state name inside. Transitions : Represents the movement from one state to another in response to events or triggers. Transitions are usually depicted as arrows connecting states, with labels indicating the events or conditions that cause the transition. Events : External stimuli or occurrences that trigger a transition from one state to another. Events are usually represented by labels on transitions. Actions : Activities or behaviors that occur when a transition is triggered. Actions are often associated with transitions and can be depicted as labels or separate elements. Initial State : Represents the starting point of the state machine. It's typically depicted as a filled circle. Final State : Represents the ending point of the state machine or the termination of a process. It's usually depicted as a filled circle surrounded by a larger circle.

State Chart Diagram

State Chart Diagram

UML Activity Diagram Depicts the flow of control or workflow of a system, process, or algorithm Illustrates the sequence of activities or actions that need to be performed and the order in which they occur Used for modeling business processes, workflow systems, use cases, and software behaviors.

Components of a UML Activity Diagram Activity Represents a specific action, operation, or step in the workflow. Activities are typically depicted as rounded rectangles with the activity name inside. Control Flow Represents the sequence of activities or actions and the order in which they occur. Control flow arrows (also called control edges) connect activities, indicating the flow of control from one activity to another. Decision Nodes Represents a decision point where the flow of control can diverge based on certain conditions or criteria. Decision nodes are depicted as diamonds, and control flow arrows leaving the decision node represent different possible outcomes or paths. Merge Nodes Represents a point where multiple control flows converge back into a single flow. Merge nodes are depicted as diamonds with multiple incoming control flow arrows. Initial Node Represents the starting point of the activity diagram. It's typically depicted as a filled circle. Final Node Represents the ending point of the activity diagram or the completion of the process. It's usually depicted as a filled circle surrounded by a larger circle. Fork and Join Nodes Represents parallel execution of activities. Fork nodes split the control flow into multiple concurrent flows, while join nodes synchronize the concurrent flows back into a single flow. Object Nodes Represents objects or data involved in activities. Object nodes can be used to show the input, output, or intermediate data of activities

UML Activity Diagram

UML Activity Diagram

UML Activity Diagram Example

UML Activity Diagram Example

UML Activity Diagram Example

UML Activity Diagram Example