21csc101t Oodp Unit-3
21csc101t Oodp Unit-3
21csc101t Oodp Unit-3
UNIT-3
Unit 3 :
02 Syntax
1. Code Reusability
04 Advantages 2. Method Overriding (Hence, Runtime Polymorphism.)
3. Use of Virtual Keyword
Inheritance Types
01 Single 02 Multiple 03 Hierarchical
04 Multilevel
05 Hybrid
Modes of
Inheritance
If we derive a sub class from a public base class. Then the public
01 Public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived
class
If we derive a sub class from a Protected base class. Then both public
02 Protected
member and protected members of the base class will become
protected in derived class.
If we derive a sub class from a Private base class. Then both public
03 private member and protected members of the base class will become
Private in derived class.
Syntax:
class Classname // base class
{
..........
};
class classname: access_specifier baseclassname
{
…
};
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();
class derived : public base //single derived
{ a.readdata();
int y;
public: a.product();
void readdata()
{ return 0;
cout << "Enter the value of y = "; }
cin >> y;
}
Applications of Single Inheritance
Student
Multiple Inheritance
Syntax:
class A // base class
{
..........
};
class B
{
..........
}
class c : access_specifier A, access_specifier B // derived class
{
...........
};
Example:
#include using namespace std;
class sum1 cout<<“enter n2″;
{ cin>>n2;
protected: int n1; cout<<“sum=”<
}; cout<<“sum=”<<n1+n2<<endl;
class sum2 }
{ };
protected: int n2; int main()
}; {
class show : public sum1, public show ob;
sum2 ob.total();
{ }
public: int total()
{
cout<<“enter n1”;
cin>>n1;
Applications of Multiple Inheritance
➢ Distributed Database
MCQ Questions
• What are the things are inherited from the base class?
A. Constructor and its destructor
B. Operator=() members
C. Friends
D. All of the above
MCQ Questions
• What are the things are inherited from the base class?
A. Constructor and its destructor
B. Operator=() members
C. Friends
D. All of the above
MCQ Questions
using namespace std; int main()
class Base1 { {
public: Derived d;
Base1() return 0;
{ cout << " Base1" << endl; } }
};
class Base2 { A. Compiler Dependent
public: B. Base1 Base2 Derived
Base2() C. Base2 Base1 Derived
{ cout << "Base2" << endl; } D. Compiler Error
};
class Derived: public Base1, public Base2 {
public:
Derived()
{ cout << "Derived" << endl; }
};
MCQ Questions
using namespace std; int main()
class Base1 { {
public: Derived d;
Base1() return 0;
{ cout << " Base1" << endl; } }
};
class Base2 { A. Compiler Dependent
public: B. Base1 Base2 Derived
Base2() C. Base2 Base1 Derived
{ cout << "Base2" << endl; } D. Compiler Error
};
class Derived: public Base1, public Base2 {
public:
Derived()
{ cout << "Derived" << endl; }
};
MCQ Questions
A. Multiple
B. Multilevel
C. Hierarchical
D. Single
MCQ Questions
A. Multiple
B. Multilevel
C. Hierarchical
D. Single
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
{
..........
}
class C : access_specifier B
// derived class
{
...........
};
public:
// base class car()
class Vehicle {
{ cout<<"Car has 4 Wheels”;
public: }
Vehicle() };
{ // main function
cout << "This is a Vehicle"; int main()
} {
}; //creating object of sub class will
class fourWheeler: public Vehicle //invoke the constructor of base classes
{ public: Car obj;
fourWheeler() return 0;
{ }
cout<<"Objects with 4 wheels are
vehicles"<<endl;
}
};
// sub class derived from two base classes
class Car: public fourWheeler{
Hierarchical Inheritance
• In Hierarichal Inheritance we
have several classes that are
derived from a common base
class (or parent class).
• Here in the diagram Class 1,
Class 2 and Class 3 are derived
from a common parent class
called Base Class.
Hierarchical Inheritance
How to implement Hierarchal Inheritance in C++
class A {
// Body of Class A • In the example present in the left we have
}; // Base Class class A as a parent class and class B and
class C that inherits some property of Class
A.
class B : access_specifier A
{ • While performing inheritance it is
// Body of Class B necessary to specify the access_specifier
which can be public, private or protected.
}; // Derived Class
class C : access_specifier A
{
// Body of Class C
}; // Derived Class
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;
} }
};
Example of Hierarchical Inheritance
Points to Remember
private: {
------------- ----------------
public: ----------------
➢ All the functions defined inside the class are implicitly inline. Thus, all the restrictions of inline
functions are also applied here.
➢ If you need to explicitly declare inline function in the class then just declare the function inside
the class and define it outside the class using inline keyword
#include <iostream>
using namespace std;
class operation inline void operation :: sum()
{ {
int a,b,add; add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
public: }
void get();
void sum(); int main()
}; {
inline void operation:: get() cout << "Program using inline function\n";
{ operation s;
cout << "Enter first value:"; s.get();
cin >> a; s.sum();
cout << "Enter second return 0;
value:"; }
cin >> b;
}
Output:
Enter first value: 45 Enter second value: 15 Addition of two numbers: 60 Difference of two numbers: 30 Product of two numbers : 675 Division of two numbers: 3
Friend Function
1. The main concepts of the object oriented programming paradigm are data hiding and data encapsulation.
2. Whenever data variables are declared in a private category of a class, these members are restricted from
accessing by non – member functions.
3. The private data values can be neither read nor written by non – member functions.
4. If any attempt is made directly to access these members, the compiler will display an error message as
“inaccessible data type”.
5. The best way to access a private data member by a non – member function is to change a private data member
to a public group.
6. When the private or protected data member is changed to a public category, it violates the whole concept or
data hiding and data encapsulation.
7. To solve this problem, a friend function can be declared to have access to these data members.
8. Friend is a special mechanism for letting non – member functions access private data.
9. The keyword friend inform the compiler that it is not a member function of the class.
Friend Function
Granting Friendship to another Class
Syntax
1. A class can have friendship with another class.
2. For Example, let there be two classes, first and second. If
01
the class first grants its friendship with the other class class second; forward declaration
second, then the private data members of the class first class first
are permitted to be accessed by the public members of the
class second. But on the other hand, the public member {
functions of the class first cannot access the private private:
members of the class second.
--------------
Friend Function
Two classes having the same Friend
Syntax
1. A non – member function may have friendship
with one or more classes. 01 friend return_type function_name(parameters);
Note:
where friend is a keyword used as a function
modifier. A friend declaration is valid only
03 within or outside the class definition.
Friend Function
Case 2:
Syntax:
class second; forward declaration
class sample
class first
{
{
private:
private:
int x;
--------------
float y;
public:
public:
friend return_type fname(first one, second two);
virtual void display();
};
virtual static int sum()
class second
}
{
int sample::sum()
private:
{}
------------------
public:
friend return_type fname(first one, second two);
};
Friend Function Example
class sample Example: void main()
{ {
private: clrscr();
int x;
public: sample obj;
void getdata();
friend void display(sample abc); obj.getdata();
}; cout<<"Accessing the private data by non
void sample::getdata() member function"<<endl;
{ display(obj);
cout<<"Enter a value for x\n"<<endl;
cin>>x; getch();
} }*/
void display(sample abc)
{
cout<<"Entered Number is "<<abc.x<<endl;
}
Friend Function Example
class first Example: }
{
friend class second; void second::disp(first temp)
private: {
int x; cout<<"Entered Number is = "<<temp.x<<endl;
public: }
void getdata();
}; void main()
{
class second
{ first objx;
public: second objy;
void disp(first temp); objx.getdata();
}; objy.disp(objx);
}
void first::getdata()
{
cout<<"Enter a Number ?"<<endl;
cin>>x;
Friend Function Example
class second; //Forward void first::getdata() int temp;
Declaration { temp = one.x + two.y;
class first cout<<"Enter a Value for X"<<endl; return(temp);
{ cin>>x; }
private: } void main()
int x; void second::getdata() {
public: { first a;
void getdata(); cout<<"Enter a value for Y"<<endl; second b;
void display(); cin>>y; a.getdata();
friend int sum(first one,second two); } b.getdata();
}; void first::display() a.display();
class second { b.display();
{ cout<<"Entered Number is X = "; int te = sum(a,b);
private: } cout<<"Sum of the two
int y; void second::display() Private data variable (X + Y)";
public: { cout<<" = "<<te<<endl;
void getdata(); cout<<"Entered Number is Y = ";
void display(); } }
friend int sum(first one,second two); int sum (first one,second two)
}; {
Virtual function
• Virtual Function is a function in base class, which is
overridden in the derived class, and which tells the Syntax
compiler to perform Late Binding on this function.
01 virtual return_type function_name (arg);
• Virtual Keyword is used to make a member function of
the base class Virtual. Virtual functions allow the most Example
specific version of a member function in an inheritance virtual void show()
hierarchy to be selected for execution. Virtual 02 {
functions make polymorphism possible. cout << "Base class\n";
Key: }
voi d s how()
{
cout <<“Implementation of Virtual Function in Derived class”;
} Output : Implementation of Virtual Function in Derived class
};
In the above example Base class is abstract, with pure virtual
show() function, hence we cannot create object of base class.
Example2 int main() {
Square square;
// C++ program to calculate the area of a square // Deri ved class
and a circle Circle circle;
cl a ss Square : public Shape {
#i ncl ude <iostream> cout << "Enter the length of the square:
publ ic: ";
us i ng namespace std;
fl oat ca lculateArea() { square.getDimension();
// Abstract class
return di mension * dimension; }
cl a ss Shape { cout << "Area of square: " <<
}; square.calculateArea() << endl;
protected:
fl oat dimension;
// Deri ved class cout << "\nEnter radius of the circle: ";
cl a ss Ci rcle : public Shape { circle.getDimension();
publ ic:
publ ic:
voi d getDimension() { cout << "Area of circle: " <<
fl oat calculateArea() { circle.calculateArea() << endl;
ci n >> di mension;
return 3.14 * di mension * dimension; return 0;
} Output
} }
// pure virtual Function
}; Enter the length of the square: 4
vi rtua l float calculateArea() = 0;
}; Area of square: 16
Enter radius of the circle: 5
Area of circle: 78.5
What will be the output of the following program?
#include <iostream>
#include <string>
using namespace std;
class Exam
{
int a;
public:
virtual void score() = 0;
};
class FirstSemExam: public Exam
a) Class B
{
b) Error
public:
c) Segmentation fault
void score(){
cout<<“First Semester Exam"<<endl;
d) No output
}
};
int main(int argc, char const *argv[]) For abstract class Exam object cannot be instantiated
{
Exam e;
e.score();
return 0;
}
Quiz
a. void area();
b. void area()=0;
c. void area()=1;
b. Incomplete type
b. Class is generic
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
When to use Interface?
• Use an interface when an immutable contract is really intended .
• Interfaces are better suited in situations when your applications
require many possibly unrelated object types to provide certain
functionality.
• Interfaces are better in situations in which you do not need to inherit
implementation from a base class.
• Interfaces can be used for multiple inheritance.
Difference between abstract class and interface
Difference between abstract class
and interface
What is similar to interface in c++
A. methods
B. instance of class
C. pure abstract class
D. friend function
Which of the following is used to
implement the c++ interfaces?
• A. absolute variables
• B. abstract classes
• C. Constant variables
• D. default variables
Practice Questions- MCQ
Which of the following Combines two concurrent activities and re-
introduces them to a flow where only one activity can be performed
at a time?
A. Joint symbol
B. Fork symbol
C. Decision symbol
D. Note symbol
Ans: A
State chart Diagram
State diagram
• A state diagram is used to represent the condition of the system or
part of the system at finite instances of time. It’s
a behavioural diagram and it represents the behaviour using finite
state transitions. State diagrams are also referred to as State
machines and State-chart Diagrams.
Uses of state chart diagram
• State chart diagrams are useful to model reactive systems
-Reactive systems can be defined as a system that responds to external or internal events.
• State chart diagram describes the flow of control from one state to
another state.
Purpose
Following are the main purposes of using State chart diagrams:
➢ To model dynamic aspect of a system.
➢To model life time of a reactive system.
➢ To describe different states of an object during its life time.
➢ Define a state machine to model states of an object.
Difference between state diagram and
flowchart
➢The basic purpose of a state diagram is to portray various changes in state of the
class and not the processes or commands causing the changes.
➢ However, a flowchart on the other hand portrays the processes or commands that
on execution change the state of class or an object of the class.
When to use State charts
➢So the main usages can be described as:
➢ To model object states of a system.
➢ To model reactive system. Reactive system consists of reactive
objects.
➢ To identify events responsible for state changes.
➢ Forward and reverse engineering.
How to draw state charts
Before drawing a State chart diagram we must have clarified the following points:
✓Identify important objects to be analysed.
✓ Identify the states.
✓Identify the events.
Elements of state chart diagrams
• Initial State: This shows the starting point of the state chart diagram that is where
the activity starts.
Elements of state chart diagrams
• State: A state represents a condition of a modelled entity for which some action is
performed. The state is indicated by using a rectangle with rounded corners and
contains compartments
Elements of state chart diagrams
• Composite state – We use a rounded rectangle to represent a
composite state also. We represent a state with internal activities
using a composite state.
Elements of state chart diagrams
• Fork – We use a rounded solid rectangular bar to represent a Fork notation with
incoming arrow from the parent state and outgoing arrows towards the newly
created states. We use the fork notation to represent a state splitting into two or
more concurrent states.
Elements of state chart diagrams
• Join – We use a rounded solid rectangular bar to represent a Join notation with
incoming arrows from the joining states and outgoing arrow towards the common
goal state. We use the join notation when two or more states concurrently
converge into one on the occurrence of an event or events.
Elements of state chart diagrams
• Transition: It is indicated by an arrow. Transition is a relationship between two
states which indicates that Event/ Action an object in the first state will enter the
second state and performs certain specified actions.
Elements of state chart diagrams
• Transition – We use a solid arrow to represent the transition or change of control
from one state to another. The arrow is labelled with the event which causes the
change in state.
Elements of state chart diagrams
• Self transition – We use a solid arrow pointing back to the state itself to represent
a self transition. There might be scenarios when the state of the object does not
change upon the occurrence of an event. We use self transitions to represent such
cases.
Elements of state chart diagrams
• Final State: The end of the state chart diagram is represented by a solid circle
surrounded by a circle.
Example state chart for ATM card PIN Verification
•
Example state chart for order management system
Activity Diagram
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.
Symbols and Notations
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
Synchronization
Symbols and Notations
Time Event
◻ This refers to an event that stops the flow for a time; an hourglass depicts
it.
Symbols and Notations
Merge Event
◻ A merge event brings together multiple flows that are not concurrent.
Ans: C
Practice questions
1. Identify all of the activities in this diagram.