0% found this document useful (0 votes)
5 views16 pages

Unit-3 Oodp

Unit-3 of the Object Oriented Design and Programming course covers various inheritance types in OOP, including single, multilevel, hierarchical, multiple, and hybrid inheritance. It also discusses key concepts such as dynamic polymorphism, virtual functions, friend functions, inline functions, abstract classes, and UML diagrams like state chart and activity diagrams. The document provides code examples to illustrate these concepts and their applications in C++.

Uploaded by

bharathrajkrish7
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)
5 views16 pages

Unit-3 Oodp

Unit-3 of the Object Oriented Design and Programming course covers various inheritance types in OOP, including single, multilevel, hierarchical, multiple, and hybrid inheritance. It also discusses key concepts such as dynamic polymorphism, virtual functions, friend functions, inline functions, abstract classes, and UML diagrams like state chart and activity diagrams. The document provides code examples to illustrate these concepts and their applications in C++.

Uploaded by

bharathrajkrish7
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/ 16

Unit-3: 21CSC101T - Object Oriented Design and Programming

Session Topics
1 Inheritance – Types
2 Single and Multiple Inheritance
3 Multilevel Inheritance - Hierarchical Inheritance
4 Hybrid Inheritance
5 Advanced Functions - Inline, Friend
6 Virtual - Pure Virtual function
7 Abstract class
8 UML State Chart Diagrams
9 UML Activity Diagram

INHERITANCE

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one


class to inherit the state (properties or instance variables) and behavior (methods) of another
class.
● Base Class: A base class is a class that is inherited by another class. The base class
provides a set of attributes and methods that can be used by the derived class. The base
class is the more general class, and it defines the common characteristics and behavior
of a group of related classes.
● Derived Class: A derived class is a class that inherits the attributes and methods of a
base class. The derived class is a specialized version of the base class and adds new
attributes and methods or overrides the ones inherited from the base class. The derived
class is the more specific class, and it defines the unique characteristics and behavior
of a specific type of object.
Base Class => Parent Class => Super Class
Derived Class => Child Class => Sub Class

class DerivedClass : inheritance_mode BaseClass {


// Derived class members
};

School of Computer Science Engineering, SRMIST-RMP 1


Unit-3: 21CSC101T - Object Oriented Design and Programming

● DerivedClass: The name of the derived class.


● inheritance_mode: The mode of inheritance, which can be public, private, or protected.
○ Public inheritance means public and protected members of the base class
become public and protected members of the derived class.
○ Private inheritance means the public and protected members of the base class
become private in the derived class.
○ Protected inheritance means the public and protected members of the base class
become protected in the derived class.
● BaseClass: The name of the base class.

Inheritance: UML Notation

/*Inheritance Demo*/
#include <iostream>
using namespace std;

// Base Class

School of Computer Science Engineering, SRMIST-RMP 2


Unit-3: 21CSC101T - Object Oriented Design and Programming

class Person {
protected:
string name;
int age;

public:
// Constructor
Person(string n, int a) : name(n), age(a) {}

// Method to display basic information


void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Derived Class - Inheriting from Person


class Student : public Person {
private:
int studentID;

public:
// Constructor (calling the base class constructor)
Student(string n, int a, int id) : Person(n, a), studentID(id) {}

// Method to display student-specific details


void displayStudentInfo() {
displayInfo(); // Accessing base class method
cout << "Student ID: " << studentID << endl;
}
};

int main() {
// Create a Student object
Student stud("Rahul", 20, 1001);

// Display student information


stud.displayStudentInfo();

return 0;
}

School of Computer Science Engineering, SRMIST-RMP 3


Unit-3: 21CSC101T - Object Oriented Design and Programming

Types of Inheritance
● Single Inheritance
● Multilevel Inheritance
● Hierarchical Inheritance
● Multiple Inheritance
● Hybrid Inheritance

Single Inheritance
In single inheritance an object or class may only inherit from one particular object or class.

Multilevel Inheritance
Multilevel inheritance is a type of inheritance where a class is derived from a class that is also
derived from another class. This forms a hierarchical chain where properties and methods are
passed from one class to the next through multiple levels.

Hierarchical Inheritance
Hierarchical inheritance is a type of inheritance where multiple child classes inherit from a
single base class. This forms a structure where one class is shared as a common parent for
several derived classes.

School of Computer Science Engineering, SRMIST-RMP 4


Unit-3: 21CSC101T - Object Oriented Design and Programming

Multiple Inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in
which an object or class can inherit characteristics and features from more than one parent
object or parent class.

Multiple inheritance leads to the “Diamond Inheritance” problem. C++ uses the Virtual
Inheritance concept to solve this problem. Virtual inheritance is a C++ technique that ensures
only one copy of a base class's member variables are inherited by grandchild derived classes.
Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits
from both B and C, then D will contain two copies of A's member variables: one via B, and
one via C.

Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance (single, multiple,
multilevel, or hierarchical) in a single program. It allows for a more flexible structure but can
introduce complexity and ambiguity, especially with diamond problems (when a class inherits
from two classes that both inherit from a common base class).

DYNAMIC POLYMORPHISM

● The decision to invoke which function to be called is made at run-time.


● Inheritance is required for achieving dynamic polymorphism.
● It is achieved by method or function overriding.
● Using virtual functions, we can achieve method overriding.

Benefits of Dynamic Polymorphism


● Extensibility
○ It is the ability to add new features.

School of Computer Science Engineering, SRMIST-RMP 5


Unit-3: 21CSC101T - Object Oriented Design and Programming

○ It follows the Open/Closed Principle. It means that the system is open for
extension but closed for modification (i.e., no changes required in existing
code).
● Flexibility
○ It is the ability to change the implementation.
○ Derived class objects can be substituted where base class objects are expected
(Liskov Substitution Principle).

Virtual Functions
● A virtual function is a member function whose behavior can be redefined (overridden)
in derived classes.
● But it is not compulsory for a normal virtual function to get overridden in derived
class.

/*Runtime Polymorphism & Virtual Function Demo*/

#include <iostream>
using namespace std;

class Batsman {
protected:
float average;
public:
Batsman(float average){
this->average = average;
}

virtual void scoreRuns(){


cout<<"I bat conservatively"<<endl;
cout<<"My average is:"<<average<<endl;
}
};

//Derived Class AggressiveBatsman


class AggressiveBatsman:public Batsman {
private:
float strikeRate;

School of Computer Science Engineering, SRMIST-RMP 6


Unit-3: 21CSC101T - Object Oriented Design and Programming

public:
AggressiveBatsman(float average, float strikeRate):
Batsman(average),strikeRate(strikeRate) {}

void scoreRuns(){
cout<<"I bat aggressively"<<endl;
cout<<"My average is:"<<average<<endl;
cout<<"My strike rate is:"<<strikeRate<<endl;
}
};

int main(){
Batsman *B, BRef(56.67);
AggressiveBatsman AB(48.54,99.97);
B = &AB;
B->scoreRuns();
B = &BRef;
B->scoreRuns();
}

Pure Virtual Functions


● A pure virtual function is a virtual function for which we do not have an
implementation.
● Syntax: virtual <function_type> <function_name>() = 0;
● Example: virtual void display()=0;
● The derived class must redefine the pure virtual function of the base class. Otherwise,
that derived class will become abstract as well.
● Whereas when using normal virtual function, overriding in derived class is not
compulsory.

FRIEND FUNCTION

A friend function in C++ is a non-member function that is granted access to the private,
protected, and public members of a class when declared as a friend.

School of Computer Science Engineering, SRMIST-RMP 7


Unit-3: 21CSC101T - Object Oriented Design and Programming

class ClassName
{
friend dataType functionName(arguments);
};

● A global function or a member function of another class, both can be declared as a


friend function.
● A friend function in C++ can be declared anywhere in the class, that is, in the public
section or the private section of the class.
● The friend function in C++ can be called just like a normal function using any instance
of any class (object).
● A friend function in C++ cannot directly access the protected or private data members
of the class. It is required to use an object and then use the dot operator (.) to access the
data members.
● Friend functionality in C++ is not restricted to only one class. That is, it can be a friend
to many classes.
● Friend functions in C++ can use objects (instance of a class) as arguments.

/*Friend Function Demo*/


#include <iostream>
using namespace std;

class Travel
{
private:
int speed;
int distance;

public:
void set_values (int a, int b)
{
speed = a;
distance = b;
}

School of Computer Science Engineering, SRMIST-RMP 8


Unit-3: 21CSC101T - Object Oriented Design and Programming

// friend function declaration


friend double findTimeofTravel (Travel);
};

// friend function definition


double findTimeofTravel (Travel t)
{
double time = (double)t.distance / (double)t.speed;
return time;
}

int main ()
{
Travel t;
t.set_values(10, 30);

/*Call the global friend function to calculate the time taken for
the Travel.*/
cout << "Time of Travel: " << findTimeofTravel (t) << " hrs" <<
endl;
return 0;
}

Friend Class
● Classes can also be declared as a friend of another class.
● A friend class is a class all of whose member functions are friend functions of a class,
that is, whose member functions have access to the other class's private and protected
members.

class ClassName
{
friend class FriendClass; // declaring friend class
};

class FriendClass
{
};

School of Computer Science Engineering, SRMIST-RMP 9


Unit-3: 21CSC101T - Object Oriented Design and Programming

/*Friend Class Demo*/


#include <iostream>
using namespace std;

/*Forward declaration so we can use it in the definition of friend


function in the Square class.*/
class Shape;

class Square
{
private:
int side;
public:
void set_values (int s)
{
side = s;
}
friend class Shape; // friend class
};

class Shape
{
public:
void print_area (Square& s)
{
// Shape is a friend class of Square class.
// It can access the side member of the Square class.
int area = s.side*s.side;
cout<<"The area of the Square is: "<<area<<endl;
}
};

int main ()
{
Square s;
s.set_values(5);
Shape sh;
sh.print_area(s);
return 0;
}

School of Computer Science Engineering, SRMIST-RMP 10


Unit-3: 21CSC101T - Object Oriented Design and Programming

INLINE FUNCTION

● The inline keyword suggests that the compiler substitute the code within the function
definition in place of each call to that function.
● Using inline functions can make your program faster because they eliminate the
overhead associated with function calls.

When to use
● Inline functions are best used for small functions, such as those that provide access to
data members. Short functions are sensitive to the overhead of function calls.
● Longer functions spend proportionately less time in the calling and returning sequence
and benefit less from inlining.

/*Inline Function*/
#include <iostream>
using namespace std;

class Computation{
private:
int num1,num2;
public:

int add(int num1, int num2);


/*
//Inline Function Expanded avoiding function call overhead
int Computation::add(int num1,int num2){
return num1+num2;
}
*/
int sub(int num1, int num2);
int mul(int num1, int num2);
float div(int num1, int num2);
};

inline int Computation::add(int num1,int num2){


return num1+num2;
}

School of Computer Science Engineering, SRMIST-RMP 11


Unit-3: 21CSC101T - Object Oriented Design and Programming

inline int Computation::sub(int num1,int num2){


return num1-num2;
}

inline int Computation::mul(int num1,int num2){


return num1*num2;
}

inline float Computation::div(int num1,int num2){


return (float)num1/num2;
}

int main(){
Computation comp;
cout<<"Addition:"<<comp.add(12,19)<<endl;
cout<<"Subtraction:"<<comp.sub(12,19)<<endl;
cout<<"Multiplication:"<<comp.mul(12,19)<<endl;
cout<<"Division:"<<comp.div(12,19)<<endl;
}

ABSTRACT CLASS

● An abstract class in C++ is a class that cannot be instantiated.


● It is meant to be used as a base class for other classes to derive from.
● An abstract class contains at least one pure virtual function.

/*Abstract Class Demo*/


#include <iostream>

using namespace std;

class Employee{
protected:
int employeeID;
string employeeName;
float experienceNumYears;

School of Computer Science Engineering, SRMIST-RMP 12


Unit-3: 21CSC101T - Object Oriented Design and Programming

public:
virtual void getEmployeeDetails(){
cin>>employeeID;
cin>>employeeName;
cin>>experienceNumYears;
}
virtual void display()=0; //Pure Virtual Function
};

//Derived Class Doctor


class Doctor:public Employee{
private:
string specialization;
public:
void getEmployeeDetails(){
cin>>employeeID;
cin>>employeeName;
cin>>experienceNumYears;
cin>>specialization;
}
void display() {
cout<<employeeID<<endl;
cout<<employeeName<<endl;
cout<<experienceNumYears<<endl;
cout<<specialization;
}
};

int main(){
Employee *emp;
Doctor doc;
emp=&doc;
emp->getEmployeeDetails();
emp->display();
}

Interface
● Interface: All functions are abstract.
● Abstract class: At least one function is abstract. All the functions need not be abstract.
● Java has both abstract class and interface constructs.

School of Computer Science Engineering, SRMIST-RMP 13


Unit-3: 21CSC101T - Object Oriented Design and Programming

● C++ have only abstract class constructs and doesn't have interface constructs.
● But we can simulate interface in C++ by making all virtual functions pure.

STATE CHART DIAGRAMS

● State Machine Diagrams (formerly called state chart diagrams in UML 1.x) depict the
dynamic behavior of an entity based on its response to events.
● It shows how the entity reacts to various events depending on the current state that it is
in.

State Diagram Components


● States
● Initial and final states
● Transitions
● State actions
● Fork and join

School of Computer Science Engineering, SRMIST-RMP 14


Unit-3: 21CSC101T - Object Oriented Design and Programming

State Chart Diagram Notations

Fig: State Chart Diagram Notations

State Chart Diagram Example

Fig: State Chart Diagram for Online Shopping

School of Computer Science Engineering, SRMIST-RMP 15


Unit-3: 21CSC101T - Object Oriented Design and Programming

ACTIVITY DIAGRAM

● A UML activity diagram offers rich notation to show a sequence of activities.


● It may be applied to any purpose (such as visualizing the steps of a computer algorithm),
but is considered especially useful for visualizing business workflows and processes,
or use cases.
● Formally, an activity diagram is considered a special kind of UML statechart diagram
in which the states are actions, and event transition is automatically triggered by action
completion.

State chart Diagram vs Activity Diagram


● State chart diagrams focus on the internal state of an object or system and how it
responds to external events.
● While activity diagrams focus on the sequence of activities involved in a process or
workflow.

Fig: Activity Diagram for Purchase Order

School of Computer Science Engineering, SRMIST-RMP 16

You might also like