Unit III - OODP (5) CPP

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 71

Unit III

• Single and Multiple Inheritance - Multilevel


inheritance - Hierarchical - Hybrid Inheritance -
Advanced Functions - Inline - Friend - Virtual -
Overriding - Pure virtual function -Abstract class and
Interface -UML State Chart Diagram - UML Activity
Diagram.
Inheritance
• Inheritance is one of the key features of Object-oriented programming
in C++.
• Inheritance is a mechanism of reusing and extending existing classes
without modifying them.
• Inheritance is a process in which one object acquires all the properties
and behaviors of its parent object automatically.
Inheritance
• We group the "inheritance concept" into two categories:
base class (parent)(Super class) - the class being inherited from.
derived class (child)(subclass) - the class that inherits from
another class.
• That is, it is possible to inherit attributes and methods from one class
to another.

Syntax: class classname: access_specifier base classname


Base and Derived Class -Example
#include <iostream>
using namespace std;
// base class int main() {
class Animal { // Create object of the Dog class
public: Dog dog1;
void eat() {
cout << "I can eat!" << endl; // Calling members of the base class
} dog1.eat();
void sleep() { dog1.sleep();
cout << "I can sleep!" << endl;
} // Calling member of the derived class
}; dog1.bark();
// derived class
class Dog : public Animal { return 0;
}
public: Output:
void bark() { I can eat!
cout << "I can bark! << endl; I can sleep!
} I can bark!
};
Inheritance -Advantages
• It allows the code to be reused as many times as needed.
• The base class once defined and once it is compiled, it need not be
reworked.
• Saves time and effort as the main code need not be written again.
Access Specifiers -Visibility modes
• Public: When the member is declared as public, it is
accessible to all the functions of the program.
• Private: When the member is declared as private, it is
accessible within the class only.
• Protected: When the member is declared as protected,
it is accessible within its own class as well as the class
immediately derived from it.

Base class Derived class visibility


visibility
Public Private Protected

Private Not Inherited Not Inherited Not Inherited


Protected Protected Private Protected
Public Public Private Protected
Access Modes
• The various ways we can derive classes are known as access
modes. These access modes have the following effect:
• Public: If a derived class is declared in public mode, then the class Animal {
members of the base class are inherited by the derived class just // code
};
as they are.
• Private: In this case, all the members of the base class become class Dog : private Animal {
private members in the derived class. // code
};
• Protected: The public members of the base class become class Cat : protected Animal
protected members in the derived class. {
// code
• The private members of the base class are always private in the };
derived class.
Visibility Modes of Inheritence

• Public Visibility mode gives the least privacy to the attributes of the base class.
• If the visibility mode is public, it means that the derived class can access the
public and protected members of the base class, but not the private members of
the base class.
• Public Visibility mode gives the most privacy to the attributes of the base class.
• If the visibility mode is private, that means that the derived class can privately
access the public and protected members of the base class.
• The access modifier protected is especially relevant when it comes to C++
inheritance.
• Protected members are needed if we want to hide the data of a class, but still
want that data to be inherited by its derived classes.
• Protected visibility mode is somewhat between the public and private modes.
• If the visibility mode is protected, that means the derived class can access the
public and protected members of the base class protectively.
Visibility Modes of Inheritence
Protected -Example
#include <iostream>
#include <string>
using namespace std;
class Animal { // Base class int main() {
private: // Create object of the Dog class
// derived class Dog dog1;
string color; class Dog : public Animal {
protected: // Calling members of the base
string type; class
public: dog1.eat();
public: void setType(string tp) {
void eat() { dog1.sleep();
type = tp; dog1.setColor("black");
cout << "I can eat!" << endl; }
} // Calling member of the derived
void displayInfo(string c) { Output:
void sleep() { class
cout << "I am a " << type << endl; I can eat!
cout << "I can sleep!" << endl; cout << "My color is " << c << endl; dog1.bark(); I can sleep!
} dog1.setType("mammal");
} I can bark!
void setColor(string clr) { // Using getColor() of dog1 as
void bark() { I am a mammal
color = clr; argument
cout << "I can bark!" << endl; My color is black
} // getColor() returns string data
} dog1.displayInfo(dog1.getColor());
string getColor() { };
return color; return 0;
}}; }
Types of Inheritance

 Single inheritance

 Multilevel inheritance

 Multiple inheritance

 Hybrid inheritance

 Hierarchical inheritance
Types of Inheritance

Multiple inheritance

Single Level
inheritance

Multilevel inheritance Hierarchical inheritance

Hybrid inheritance
Single Inheritance
• In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is
inherited from one base class only.
• Based on the visibility mode used or access specifier used while deriving, the properties
of the base class are derived. Access specifier can be private, protected or public.

Syntax:
class Classname // base class
{
..........
}; Application:
class classname: access_specifier baseclassname 1. University Grading System
{
2. Employee and Salary

};
Single Inheritance - Example

#include <iostream> void product()


using namespace std; {
class base //single base class cout << "Product = " << x * y;
{ public: }
int x; };
void getdata()
{ int main()
cout << "Enter the value of x = "; {
cin >> x; derived a; //object of derived class
} a.getdata();
}; a.readdata();
class derived : public base //single derived a.product();
{ return 0;
int y; }
public:
void readdata()
{
cout << "Enter the value of y = ";
cin >> y;
}
Multiple Inheritance
In this type of inheritance a single derived class may
inherit from two or more base clases.

Syntax:
class A // base class
{
..........
};
class B
{
..........
}
class c : access_specifier A, access_specifier B Application:
// derived class • Distributed Database
{
...........
};
Example: Multiple Inheritance
cout<<“enter n2″;
#include using namespace std; cin>>n2;
class sum1 cout<<“sum=”<
{ cout<<“sum=”<<n1+n2<<endl;
protected: int n1; }
}; };
class sum2
{ int main()
protected: int n2; {
}; show ob;
class show : public sum1, public sum2 ob.total();
{ }
public: int total()
{
cout<<“enter n1”;
cin>>n1;
Inheritance Ambiguity

• In multiple inheritances, when one class is derived from two or more


base classes then there may be a possibility that the base classes have
functions with the same name, and the derived class may not have
functions with that name as those of its base classes.
• If the derived class object needs to access one of the similarly named
member functions of the base classes then it results in ambiguity
because the compiler gets confused about which base’s class member
function should be called.
Ambiguity Error - Example
#include<iostream> Output:
using namespace std; // Derived class C prog.cpp: In function ‘int main()’:
prog.cpp:43:9: error: request for member
// Base class A class C: public A, public B { ‘func’ is ambiguous
obj.func();
class A { ^
public: }; prog.cpp:21:10: note: candidates are: void
B::func()
void func() { // Driver Code void func() {
cout << " I am in class A" << endl; ^
} int main() { int main() {
};
// Created an object of class C // Created an object of class C
// Base class B C obj;
C obj;
class B { Can Be // Calling function func() in class A
obj.A::func();
public: // Calling function func()
// Calling function func() in class B
void func() { obj.func(); obj.B::func();
cout << " I am in class B" << endl;
} return 0; return 0;
}
}; }
Multilevel Inheritance
A derived class can be derived from another derived class. A child class can be the parent of another
class.

Syntax:
class A // base class
{
..........
};
class B: access_Specifier class A
{
..........
}
class C : access_specifier B
// derived class
{
...........
};
Example: Multilevel Inheritance
// sub class derived from two base classes
// base class class Car: public fourWheeler
class Vehicle {
{ public:
public: car()
Vehicle() {
{ cout<<"Car has 4 Wheels”;
cout << "This is a Vehicle"; }
} };
}; // main function
class fourWheeler: public Vehicle int main()
{ public: {
fourWheeler() //creating object of sub class will
{ //invoke the constructor of base classes
cout<<"Objects with 4 wheels are Car obj;
vehicles"<<endl; return 0;
} }
};
Hierarchical Inheritance
Syntax:
class A {
// Body of Class A
}; // Base Class

class B : access_specifier A
{
// Body of Class B
}; // Derived Class

class C : access_specifier A
{
// Body of Class C
}; // Derived Class
Hierarchical Inheritance -Example
#include <iostream> class C : public A //C is also derived from
using namespace std; class base
class A //single base class {
{ public:
public: void sum()
int x, y; {
void getdata() cout << "\nSum= " << x + y;
{ }
cout << "\nEnter value of x and y:\n"; };
cin >> x >> y; int main()
} {
}; B obj1; //object of derived class B
class B : public A //B is derived from class base C obj2; //object of derived class C
{ obj1.getdata();
public: obj1.product();
void product() obj2.getdata();
{ obj2.sum();
cout << "\nProduct= " << x * y; return 0;
} }
};
Hybrid Inheritance
• Hybrid Inheritance involves derivation of more than one type of inheritance.

Syntax:
class A
{
// Class A body
};
class B : public A
{
// Class B body
};
class C
{
// Class C body
};
class D : public B, public C
{ // Class D body
};
Hybrid Inheritance - Example

class A class C
{ { public:
public: int y;
int x; C()
}; {
class B : public A y = 4;
}
{
};
public: class D : public B, public C
B() { public:
{ void sum()
x = 10; {
} cout << "Sum= " << x + y;
}; }
};
Limitations
• Constructors and Destructors are never inherited and hence never
overridden.
• Also, assignment operator = is never inherited. It can be overloaded
but can't be inherited by sub-class.
• Static member functions are inherited into the derived class.
• If you redefine a static member function in the derived class, all the
other overloaded functions in the base class are hidden.
• Static Member functions can never be virtual.
The derived class can inherit all base class methods except:
• Constructors, destructors and copy constructors of the base class.
• Overloaded operators of the base class.
• The friend functions of the base class.
Advanced Functions
• Inline function
• Friend function
• Virtual function and
• Overriding
Inline function

• The key feature of C++ is the inline function.


• If a function is inline, then the compiler replaces the function calling
location with the definition of the inline function at compile time.
• Any changes made to an inline function will require the inline function
to be recompiled.
The advantages of using inline member functions are:
1. The size of the object code is considerably reduced.
2. It increases the execution speed, and
3. The inline member functions are compact function calls.
• The compiler may not implement inlining in situations like these:
• If a function contains a loop. (for, while, do-while)
• if a function has static variables.
• Whether a function recurses.
• If the return statement is absent from the function body and the return
type of the function is not void.
• Whether a function uses a goto or switch statement.
Syntax for an inline function:
inline return_type function_name(parameters)
{
// function code
}
Inline function -Example
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
return 0;

} Output : 5
Inline function -Example

#include <iostream>
using namespace std; inline void operation :: sum()
class operation {
{ add = a+b;
int a,b,add; cout << "Addition of two numbers: " << a+b << "\n";
}
public:
void get(); int main()
void sum(); {
}; cout << "Program using inline function\n";
inline void operation:: get() operation s;
{ s.get();
cout << "Enter first value:"; s.sum(); Output:
cin >> a; return 0; Enter first value: 45
cout << "Enter second } Enter second value: 15
Addition of two numbers: 60
value:"; Difference of two numbers: 30
cin >> b; Product of two numbers: 675
} Division of two numbers: 3
The Normal Function The Inline Function
• when the function fun1() is
called, the control is transferred to • When the inline function is
the definition of the called encountered, then the definition
function. of the function is copied to it.
• The addresses from where the • In this case, there is no control
function is called and the transfer which saves a lot of
definition of the function are time and also decreases the
different. overhead.
• This control transfer takes a lot of • Eg: inline void sum( )
time and increases the overhead.
• Eg: void sum( )
Need for an Inline Function

• The main use of the inline function in C++ is to save memory space.
• Whenever the function is called, then it takes a lot of time to execute the tasks, such as moving to
the calling function.
• If the length of the function is small, then a substantial amount of execution time is spent in such
overheads.
Friend Function
• If a function is defined as a friend function in C++, then the protected
and private data of a class can be accessed using the function.
• By using the keyword friend compiler knows the given function is a
friend function.
• For accessing the data, the declaration of a friend function should be
done inside the body of a class starting with the keyword friend.
syntax of friend function
class class_name
{
friend data_type function_name(argument/s);
};
Features of Friend Function
• The function is not in the scope of the class to which it has been
declared as a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object
name and dot membership operator with the member name.
• It can be declared either in the private or the public part.
• A friend function can be:
 A global function
 A member function of another class
Friend Function - Example 1

class base {
private: //friend function definition
int pvariable; void friendFunction(base& obj)
{
cout << "Private Variable: " << obj.pvariable << endl;
protected:
cout << "Protected Variable: " << obj.provariable;
int provariable; }

public: // driver code


base() int main()
{ {
pvariable = 10; base object1;
provariable = 99; friendFunction(object1);
} return 0;
} Outut:
// friend function declaration Private Variable: 10
friend void friendFunction(base& obj); Protected Variable: 99
};
Friend Function - Example 2
using namespace std; class B void min(A a,B b)
class B; { {
// forward declarartion. int y; if(a.x<=b.y)
public: std::cout << a.x << std::endl;
class A void setdata(int i) else
{ { std::cout << b.y << std::endl;
int x; y=i; }
} int main()
public:
// friend function {
void setdata(int i) friend void min(A,B); A a;
{ x=i; } B b;
// friend function. }; a.setdata(10);
friend void min(A,B); b.setdata(20);
min(a,b);
}; return 0;
}
Output: 10
Friend Class - Example
class A
{
int x =5; int main()
friend class B; // friend class. {
// Class B can access the private members of A a;
class A. B b;
}; b.display(a);
class B return 0;
{ }
public:
void display(A &a)
{ Output
cout<<"value of x is : "<<a.x; value of x is : 5
}
};
Advantages of Friend Functions
• A friend function can access members without the need to inherit the
class.
• The friend function acts as a bridge between two classes by accessing
their private data.
• It can be used to increase the versatility of overloaded operators.
• It can be declared either in the public or private or protected part of the
class.
Disadvantages of Friend Functions
• Friend functions have access to private members of a class from outside
the class which violates the law of data hiding.
• Friend functions cannot do any run-time polymorphism in their
members.
Limitations of Friend Functions and Classes
1.Friends should be used only for limited purposes.
2.Too many functions or external classes are declared as friends of a
class with protected or private data access lessens the value of
encapsulation of separate classes in object-oriented programming.
3.Friendship is not mutual. If class A is a friend of B, then B doesn’t
become a friend of A automatically.
4.Friendship is not inherited.
Virtual Functions

• A C++ virtual function is a member function in the base class that you
redefine in a derived class.
• It is declared using the virtual keyword.
• It is used to tell the compiler to perform dynamic linkage or late
binding on the function.
• When you refer to a derived class object using a pointer or a reference
to the base class, you can call a virtual function for that object and
execute the derived class’s version of the method.
• A 'virtual' is a keyword preceding the normal declaration of a function.
• When the function is made virtual, C++ determines which function is
to be invoked at the runtime based on the type of the object pointed by
the base class pointer.
Rules for Virtual Functions
• Virtual functions cannot be static.
• A virtual function can be a friend function of another class.
• Virtual functions should be accessed using a pointer or reference of
base class type to achieve runtime polymorphism.
• The prototype of virtual functions should be the same in the base as
well as the derived class.
• They are always defined in the base class and overridden in a derived
class. The derived class doesn't need to override (or re-define the virtual
function), in that case, the base class version of the function is used.
• A class may have a virtual destructor but it cannot have a virtual
constructor.
Virtual Functions –Example 1

#include <iostream> int main()


using namespace std; {
class base { base* bptr;
derived d;
public: bptr = &d;
virtual void print() { cout << "print base // Virtual function, binded at runtime
class\n"; } bptr->print();
void show() { cout << "show base class\n"; } // Non-virtual function, binded at compile time
bptr->show();
};
return 0;
class derived : public base { }
public:
void print() { cout << "print derived class\n"; Output
} print derived class
void show() { cout << "show derived class\ show base class
n"; }
};
Virtual Functions –Example 2
class Point class Square : public Shape
{ {
protected: public:
float length,breath,side,radius,area,height; void getdata()
}; {
class Shape: public Point cout<<"Enter the Value of the Side of the
{ Box:"<<endl;
public: cin>>side;
virtual void getdata()=0; }
virtual void display()=0; void display()
}; {
area = pow(side,4);
class Rectangle:public Shape cout<<"The Area of the Square is:"<<area<<endl;
{ }
public: };
void getdata() void main()
{ {
cout<<"Enter the Breadth Value:"<<endl; Shape *s;
cin>>breath; Rectangle r;
cout<<"Enter the Length Value:"<<endl; Square t;
cin>>length; s = &r;
} s->getdata();
void display() s->display();
{ s = &t;
area = length * breath; s->getdata();
cout<<"The Area of the Rectangle is:"<<area<<endl; s->display();
} }
};
Pure Virtual Functions
• A virtual function is not used for performing any task. It only serves as
a placeholder.
• When the function has no definition, such function is known as "do-
nothing" function.
• The "do-nothing" function is known as a pure virtual function. A
pure virtual function is a function declared in the base class that has no
definition relative to the base class.
• A class containing the pure virtual function cannot be used to declare
the objects of its own, such classes are known as abstract base classes.
• The main objective of the base class is to provide the traits to the
derived classes and to create the base pointer used for achieving the
runtime polymorphism.
Example
using namespace std; int main()
class Base {
{ Base *bptr;
public: //Base b;
Derived d;
virtual void show() = 0;
bptr = &d;
}; bptr->show();
class Derived : public Base
{ return 0;
public: }
void show()
{
Output:
cout << "Derived class is derived from base
class."; Derived class is derived from base class.
}
};
Limitations of Virtual Functions

• Slower: The function call takes slightly longer due to the virtual mechanism and
makes it more difficult for the compiler to optimize because it does not know
exactly which function is going to be called at compile time.
• Difficult to Debug: In a complex system, virtual functions can make it a little
more difficult to figure out where a function is being called from.
Friend Function Virtual Function
It is non-member functions that usually have private It is a base class function that can be overridden by a
access to class representation. derived class.

It is used to ensure that the correct function is called for


It is used to access private and protected classes. an object no matter what expression is used to make a
function class.

It is declared within the base class and is usually


It is declared outside the class scope. It is declared using
redefined by a derived class. It is declared using a
the ‘friend’ keyword.
‘virtual‘ keyword.

It is generally used to give non-member function access It is generally required to tell the compiler to execute
to hidden members of a class. dynamic linkage of late binding on function.

They support sharing information of class that was


They support object-oriented programming, ensures that
previously hidden, provides method of escaping data
function is overridden, can be friend of other function,
hiding restrictions of C++, can access members without
etc.
inheriting class, etc.

It can access private members of the class even while


It is used so that polymorphism can work.
not being a member of that class.
Abstract class and Interface
• An interface describes the behaviour or capabilities of a class without
committing to a particular implementation of that class.
• In C++, we don't get a built-in interface.
• To create an interface, first, we need to create an abstract class which
is having only pure virtual methods.
• Interfaces are also called pure abstract classes.
• An abstract class is a class specially designed to be used as a base
class.
• It must have at least one pure virtual function. It may have variables
and normal functions.
• The derived classes of an abstract class must implement all the pure
virtual functions of their base class or else they too become abstract.
Importance of Interfaces in C++

• Any class that is derived from the pure abstract classes which are
called Interface must be implemented by all of the methods of the base
class.
• The pointers in the Interface can be passed to classes and functions
thereby the programmers as well as the user can call the functions of
the derived class from that particular class.
Rules of Using Interfaces
• The users have to declare only pure virtual functions without giving
their definition
• For pure virtual functions, the users can only assign 0.
• The user cannot create an instance of the class.
• Users can only create a pointer to the instance of a particular derived
class with a reference to a base class, or Abstract Classes
State Chart Diagram
• It describes different states of a component in a system. The states are
specific to a component/object of a system.
• A Statechart diagram describes a state machine. State machine can be
defined as a machine which defines different states of an object and
these states are controlled by external or internal events.
• As Statechart diagram defines the states, it is used to model the
lifetime of an object.
Example
using namespace std;
// Interface(Abstract class int main()
// with pure virtual function) {
class Scholar child childObj;
{ Scholar* ptr;
public: ptr = &childObj;
cout << ptr->returnString();
virtual string returnString() = 0;
return 0;
}; }
class child : public Scholar
{
public: Output
string returnString() OOAD
{
return “OOAD";
}
};
Purpose of State Chart Diagram
• To model the dynamic aspect of a system.
• To model the life time of a reactive system.
• To describe different states of an object during its life time.
• Define a state machine to model the states of an object.
• Statechart diagrams are also used for forward and reverse
engineering of a system.
How to Draw a Statechart Diagram?
• Statechart diagram is used to describe the states of different
objects in its life cycle.
• Emphasis is placed on the state changes upon some internal
or external events.
• Identify the important objects to be analyzed.
• Identify the states.
• Identify the events.
Notations
State Machine Diagram Flow Chart

An State Machine Diagram is associated with A Flow Chart is associated with the
the UML(Unified Modelling Language) programming.

The basic purpose of a state machine diagram A flowchart on the other hand portrays the
is to portray various changes in state of the processes or commands that on execution
class and not the processes or commands change the state of class or an object of the
causing the changes. class.

Primarily used for systems, emphasizing their Often used for processes, procedures, or
states and transitions. algorithms involving actions and decisions.
Main Usage
• To model the object states of a system.
• To model the reactive system. Reactive system consists of reactive
objects.
• To identify the events responsible for state changes.
• Forward and reverse engineering.
Activity Diagram

❑ Activity diagram is UML behavior diagram which emphasis on the


sequence and conditions of the flow
❑ It shows a sequence of actions or flow of control in a system.
❑ It is like to a flowchart or a flow diagram.
❑ It is frequently used in business process modeling. They can also describe
the steps in a use case diagram.
❑ The modeled Activities are either sequential or concurrent.
Benefits
◻ It illustrates the logic of an algorithm.
◻ It describes the functions performed in use cases.
◻ Illustrate a business process or workflow between users and the system.
◻ It Simplifies and improves any process by descriptive complex use cases.
◻ Model software architecture elements, such as method, function, and
operation.
Symbols and Notations
Activity
◻ Is used to illustrate a set of actions.
◻ It shows the non-interruptible action of objects.

Action Flow
◻ It is also called edges and paths
◻ It shows switching from one action state to another. It is represented as an
arrowed line.
Symbols and Notations
Object Flow
◻ Object flow denotes the making and modification of objects by activities.
◻ An object flow arrow from an action to an object means that the action
creates or influences the object.
◻ An object flow arrow from an object to an action indicates that the action
state uses the object.
Symbols and Notations

Decisions and Branching


◻ A diamond represents a decision with alternate paths.
◻ When an activity requires a decision prior to moving on to the next
activity, add a diamond between the two activities.
◻ The outgoing alternates should be labeled with a condition or guard
expression. You can also label one of the paths "else."
Symbols and Notations

Guards
◻ In UML, guards are a statement written next to a decision diamond that
must be true before moving next to the next activity.
◻ These are not essential, but are useful when a specific answer, such as
"Yes, three labels are printed," is needed before moving forward.
Symbols and Notations

Synchronization
◻ A fork node is used to split a
single incoming flow into
multiple concurrent flows. It is
represented as a straight,
slightly thicker line in an
activity diagram.
◻ A join node joins multiple
concurrent flows back into a
single outgoing flow.
◻ A fork and join mode used
together are often referred to as
synchronization.
Symbols and Notations
Time Event
◻ This refers to an event that stops the flow for a time; an hourglass depicts it.

Merge Event
◻ A merge event brings together multiple flows that are not concurrent.

Final State or End Point


◻ An arrow pointing to a filled circle nested inside another circle represents
the final action state.
Symbols and Notations
Swimlane and Partition
◻ A way to group activities performed by the same actor on an activity
diagram or to group activities in a single thread
Activity
Diagram
Activity
Diagram
with
Swimlane
Activity
Diagram without
Swimlane
Thank you!!!

You might also like