0% found this document useful (0 votes)
8 views86 pages

OOPs With C--_CSE 2001_ Unit 3.Pptx

The document outlines the syllabus for the Object Oriented Programming with C++ course at VIT Bhopal University, covering key concepts such as classes, objects, polymorphism, inheritance, exception handling, and templates. It explains compile-time and runtime polymorphism, including function overloading and overriding, along with examples and rules governing these concepts. Additionally, it discusses operator overloading and provides examples of how to implement these features in C++.
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)
8 views86 pages

OOPs With C--_CSE 2001_ Unit 3.Pptx

The document outlines the syllabus for the Object Oriented Programming with C++ course at VIT Bhopal University, covering key concepts such as classes, objects, polymorphism, inheritance, exception handling, and templates. It explains compile-time and runtime polymorphism, including function overloading and overriding, along with examples and rules governing these concepts. Additionally, it discusses operator overloading and provides examples of how to implement these features in C++.
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/ 86

VIT Bhopal University

Bhopal-Indore Highway, Kothri Kalan, Sehore, Madhya Pradesh – 466114.

Object Oriented Programming with C++


Course Code: CSE 2001

By:
Dr. Ramraj Dangi
● Introduction to object oriented
approach
● Classes and objects
Chapters ● Polymorphism and Inheritance
● Exception handling and Templates
● IOstreams and Files
Polymorphism
– compile time polymorphism
– function overloading
– operator overloading.

Syllabus Inheritance
– types of inheritance
– constructors and destructors in inheritance
– constraints of multiple inheritance

Abstract base class


– pure virtual functions
– runtime polymorphism
– function overriding.
Polymorphism
Polymorphism

The term "Polymorphism" is the combination of


"poly" + "morphs" which means many forms. It
is a greek word. Let's consider a real-life
example of polymorphism.

Ex. A lady behaves like a teacher in a


classroom, mother or daughter in a home and
customer in a market. Here, a single person is
behaving differently according to the situations.
Binding

Binding means matching the function call with the correct function definition by the compiler. It takes
place either at compile time or at runtime.

Early Binding
In early binding, the compiler matches the function call with the correct function definition at compile
time. It is also known as Static Binding or Compile-time Binding. By default, the compiler goes to the
function definition which has been called during compile time. So, all the function calls you have studied
till now are due to early binding.
Example

#include <iostream> int main()


using namespace std; {
class Animals Animals *a;
{ Dogs d;
public: a= &d;
void sound() a -> sound(); // early binding
{ return 0;
cout << "This is parent class" << endl; }
}
}; Now in this example, we created a pointer a to the parent class Animals. Then by writing
a= &d , the pointer 'a' started referring to the object d of the class Dogs.
class Dogs : public Animals a -> sound(); - On calling the function sound() which is present in both the classes by
{ the pointer 'a', the function of the parent class got called, even if the pointer is referring
public:
to the object of the class Dogs.
void sound()
This is due to Early Binding. We know that a is a pointer of the parent class referring to
{
the object of the child class. Since early binding takes place at compile-time, therefore
cout << "Dogs bark" << endl;
when the compiler saw that a is a pointer of the parent class, it matched the call with
}
}; the 'sound()' function of the parent class without considering which object the pointer is
referring to.
Late Binding

In the case of late binding, the compiler matches the function call with the correct function definition at
runtime. It is also known as Dynamic Binding or Runtime Binding.
In late binding, the compiler identifies the type of object at runtime and then matches the function call
with the correct function definition.
By default, early binding takes place. So if by any means we want to tell the compiler to perform late
binding, then how the problem in the previous example can be solved?

This can be achieved by declaring a “virtual function”.


Virtual Function

Virtual Function is a member function of the base class which is overridden in the derived class. The
compiler performs late binding on this function.

To make a function virtual, we write the keyword virtual before the function definition.
Example

#include <iostream> int main()


using namespace std; {
class Animals Animals *a;
{ Dogs d; a= &d;
public: a -> sound(); // late binding
virtual void sound() return 0;
{ }
cout << "This is parent class" << endl;
}
};
Since the function sound() of the base class is made virtual, the
class Dogs : public Animals
{ compiler now performs late binding for this function. Now, the
public: function call will be matched to the function definition at runtime.
void sound()
Since the compiler now identifies pointer a as referring to the
{
cout << "Dogs bark" << endl; object 'd' of the derived class Dogs, it will call the sound()
} function of the class Dogs.
};
Compile time polymorphism Runtime polymorphism
The function to be invoked is known at the compile time. The function to be invoked is known at the run time.

It is also known as overloading, early binding and static binding. It is also known as overriding, Dynamic binding and late binding.

Overloading is a compile time polymorphism where more than one Overriding is a run time polymorphism where more than one method is
method is having the same name but with the different number of having the same name, number of parameters and the type of the
parameters or the type of the parameters. parameters.

It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.

It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.

It is less flexible as mainly all the things execute at the compile time. It is more flexible as all the things execute at the run time.

Difference between Compile time and Runtime Polymorphism


Overloading
If we create two or more members having the same name but different in number or type of parameter, in
C++, it is known as overloading.
In C++, we can overload:
● methods,
● constructors
It is because these members have parameters only.

Types of overloading in C++ are:


● Function overloading
● Operator overloading
Function Overloading

● Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading in C++.
● In function overloading, the function is redefined by using either different types of arguments or a
different number of arguments.
● It is only through these differences, compiler can differentiate between the functions.
● The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.
Rules of Function Overloading

Different parameters or three different conditions :


1. These functions have different parameter type
sum(int a, int b)
sum(double a, double b)
2. These functions have a different number of parameters
sum(int a, int b)
sum(int a, int b, int c)
3. These functions have a different sequence of parameters
sum(int a, double b)
sum(double a, int b)
Rules of Function Overloading

The above three cases are valid cases of overloading. We can have any number of functions, but
remember that the parameter list must be different.

For example:
int mul(int, int)
double mul(int, int)

Note: As the parameter list is the same, this is not allowed. Even though their return types are different,
it’s not valid.
Example

#include<iostream>
using namespace std;
int mul(int,int);
int mul(float,int);

int mul(int a,int b)


{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}
Function Overriding
#include <iostream> int main() {
If derived class defines same using namespace std; Dog d = Dog();
function as defined in its base class Animal { d.eat();
public: return 0;
class, it is known as function
void eat() { }
overriding in C++. It is used to cout<<"Eating...";
achieve runtime polymorphism. }
It enables you to provide };
class Dog: public Animal {
specific implementation of the
public:
function which is already void eat() // overriding function
provided by its base class. {
cout<<"Eating bread...";
}
};
Virtual Function

● 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.
● There is a necessity to use the single pointer to refer to all the objects of the different classes. So,
we create the pointer to the base class that refers to all the derived objects. But, when base class
pointer contains the address of the derived class object, always executes the base class function.
This issue can only be resolved by using the 'virtual' function.
● 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.
S.No. Function Overloading Function Overriding

The concept through which we can define two or more The concept through which we define a function in parent
functions with the same name and different numbers and class and the child class with the same return type and
1. parameters is known as function overloading. parameters is known as function overriding.

It can take place without inheritance. It can take place only when a class inherited from another
2. class.
3. It happens during compile time. It happens during run time.
4. It is also known as compile time polymorphism. It is also known as run time polymorphism.
The function overloading can take place multiple times. Function overriding can take place in the derived class only at
5. once.
Here, the scope of the overloaded functions remain the Here, the scope of the overridden function is different.
6. same.
No keyword is used during function overloading. When the function is defined, it is preceded by 'virtual'
7. keyword in main class.

Difference between Function Overloading and Functio Overriding


Function Overloading Ambiguity

When the compiler is unable to decide which function is to be invoked among the overloaded function,
this situation is known as function overloading ambiguity.

Causes of Function Overloading:


•Type Conversion.
•Function with default arguments.
•Function with pass by reference.
Type Conversion Ambiguity in Function Overloading

#include<iostream>
The above example shows an error "call of
using namespace std;
void fun(int); overloaded 'fun(double)' is ambiguous". The
void fun(float);
fun(12) will call the first function. The fun(1.2)
void fun(int i)
{ calls the second function according to our
std::cout << "Value of i is : " <<i<< std::endl;
prediction. But, this does not refer to any
}
void fun(float j) function as in C++, all the floating point
{
constants are treated as double not as a float. If
std::cout << "Value of j is : " <<j<< std::endl;
} we replace float to double, the program works.
int main()
Therefore, this is a type conversion from float
{
fun(12); //Value of i is : 12 to double.
fun(1.2); //Value of j is : 1.2
return 0;
}
Function with default arguments ambiguity in Function Overloading

#include<iostream>
using namespace std; The above example shows an error "call of
void fun(int); overloaded 'fun(int)' is ambiguous". The fun(int
void fun(int,int);
void fun(int i) a, int b=9) can be called in two ways: first is by
{ calling the function with one argument, i.e.,
std::cout << "Value of i is : " <<i<< std::endl;
} fun(12) and another way is calling the function
void fun(int a,int b=9) with two arguments, i.e., fun(4,5). The fun(int
{
std::cout << "Value of a is : " <<a<< std::endl; i) function is invoked with one argument.
std::cout << "Value of b is : " <<b<< std::endl; Therefore, the compiler could not be able to
}
int main() select among fun(int i) and fun(int a,int b=9).
{
fun(12);

return 0;
}
Function with pass by reference ambiguity in Function Overloading

#include <iostream>
using namespace std; The above example shows an error "call of
void fun(int); overloaded 'fun(int&)' is ambiguous". The
void fun(int &);
int main() first function takes one integer argument and
{ the second function takes a reference parameter
int a=10;
fun(a); // error, which f()? as an argument. In this case, the compiler does
return 0; not know which function is needed by the user
}
void fun(int x) as there is no syntactical difference between the
{ fun(int) and fun(int &).
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}
Operator Overloading

● Operator overloading is a compile-time polymorphism in which the operator is overloaded to


provide the special meaning to the user-defined data type.
● Operator overloading is used to overload or redefines most of the operators available in C++.
● It is used to perform the operation on the user-defined data type.
● For example, C++ provides the ability to add the variables of the user-defined data type that is
applied to the built-in data types.
● The advantage of Operators overloading is to perform different operations on the same operand.
Restricted Operators

Operator that cannot be overloaded are as follows:

● Scope operator (::)


● Sizeof
● member selector(.)
● member pointer selector(*)
● ternary operator(?:)
Syntax of Operator Overloading

Syntax of Operator Overloading


return_type class_name : : operator op(argument_list)
{
// body of the function.
}

return_type is the type of value returned by the function.


class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the “operator” is the
keyword.
Example: C++ Overloading unary minus(-) operator

#include<iostream> //Definition of overloaded unary minus


using namespace std; operator - function
class A { void A :: operator -()
private: {
int a; a = -a;
public: }
void set_a();
void get_a(); int main()
void operator -(); {
}; A ob;
ob.set_a(); //a = 10
//Definition of set_a() function
void A :: set_a() cout<<"The value of a is : ";
{ ob.get_a(); //10
a = 10;
} //Calling operator overloaded function -
to negate the value
//Definition of get_a() function -ob; //ob is user defined object
void A :: get_a()
{ cout<<"The value of a after calling
cout<< a <<"\n"; operator overloading function - is : ";
} ob.get_a();
}
Example: C++ Overloading unary minus (-) friend function

#include<iostream> A operator -(A ob) {


using namespace std; ob.a = -(ob.a);
return ob;
class A { }
private:
int a; int main() {
A ob;
public: ob.set_a();
void set_a();
void get_a(); cout<<"The value of a is : ";
friend A operator -(A); // Friend ob.get_a();
function which takes an object of A and
return an object of A type. //Calling operator overloaded function - to
}; negate the value
ob = -ob; //ob object is passed as an argument
void A :: set_a() { to the friend function and its negative
a = 10; version is returned.
}
cout<<"The value of a after calling operator
void A :: get_a() { overloading friend function - is : ";
cout<< a <<"\n"; ob.get_a();
} }
Example: C++ Overloading increment operator

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test() {
num = 8; }
void operator ++() {
num = num+2;
}
void print() {
cout<<"The Count is: "<<num;
}
};
int main() {
Test tt;
tt.print(); //The count is: 8
++tt; // calling of a function "void operator ++()"
tt.print(); //The count is:10
return 0;
}
Example: Overloading Binary Operator

#include <iostream> void A :: operator+(A a)


using namespace std; {
class A
{ int m = x + a.x;
cout<<"The result of the addition of
int x; two objects is : "<<m;
public:
A( ) }
{}
A(int i) int main()
{ {
x=i; A a1(5);
} A a2(4);
void operator+(A); a1+a2;
void display(); return 0;
}; }
Example: Overloading binary operator * using friend function

#include<iostream>
using namespace std;

class A {
private:
int a;
public:
void set_a();
void get_a();
friend A operator *(A,A); //Binary operator * overloaded friend function, which takes
two object of A and returns an object of A type.
};

void A :: set_a() {
a = 5;
}

void A :: get_a() {
cout<< a <<"\n";
}
Example: Overloading binary operator * using friend function

A operator *(A ob1, A ob2) {


A temp;
temp.a = ob1.a * ob2.a;
return temp;
}

int main() {
A ob1, ob2;
ob1.set_a();
ob2.set_a();

cout<<"The value of a in first object : ";


ob1.get_a();
cout<<"The value of a in second object : ";
ob2.get_a();

A ob3 = ob1 * ob2; //ob1 and ob2 objects are passed as an argument to the operator * overloaded friend function.
cout<<"The value of a after calling operator overloading function * is : ";
ob3.get_a();
}
Example

#include <iostream> Arith_num operator + (Arith_num &ob)


using namespace std; {
class Arith_num Arith_num A;
{ A.x = x + ob.y;
int x, y; return (A);
public: }
void input( ) };
{
cout << " Enter the first number: "; int main ()
cin >> x; {
} Arith_num x1, y1, res;
void input2() x1.input(); //5
{ y1.input2(); //7
cout << " Enter the second number: "; res = x1 + y1;
cin >> y; res.print();
} return 0;
void print() }
{
cout << "The sum of two numbers is: " <<x;
}
Function Overriding
#include <iostream> int main() {
If derived class defines same using namespace std; Dog d = Dog();
function as defined in its base class Animal { d.eat();
public: return 0;
class, it is known as function
void eat() { }
overriding in C++. It is used to cout<<"Eating...";
achieve runtime polymorphism. }
It enables you to provide };
class Dog: public Animal {
specific implementation of the
public:
function which is already void eat() // overriding function
provided by its base class. {
cout<<"Eating bread...";
}
};
Virtual Function

● 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.
● There is a necessity to use the single pointer to refer to all the objects of the different classes. So,
we create the pointer to the base class that refers to all the derived objects. But, when base class
pointer contains the address of the derived class object, always executes the base class function.
This issue can only be resolved by using the 'virtual' function.
● 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 of Virtual Function

● Virtual functions must be members of some class.

● Virtual functions cannot be static members.

● They are accessed through object pointers.

● They can be a friend of another class.

● A virtual function must be defined in the base class, even though it is not used.

● The prototypes of a virtual function of the base class and all the derived classes must be
identical. If the two functions with the same name but different prototypes, C++ will consider
them as the overloaded functions.
Example

#include <iostream> int main()


using namespace std; {
class A A *a;
{ B b;
int x=5; a = &b;
public: a->display();
void display() return 0;
{ }
std::cout << "Value of x is : " << x<<std::endl;
}
In above example, * a is the base class
};
pointer. The pointer can only access the
class B: public A
base class members but not the members
{ of the derived class. Although C++
int y = 10; permits the base pointer to point to any
public: object derived from the base class, it
void display() cannot directly access the members of the
{ derived class. Therefore, there is a need
std::cout << "Value of y is : " <<y<< std::endl; for virtual function which allows the base
} pointer to access the members of the
}; derived class.
Example

#include <iostream> int main()


{ {
public: A* a; //pointer of base class
virtual void display() B b; //object of derived class
{ a = &b;
cout << "Base class is invoked"<<endl; a->display(); //Late Binding occurs
} }
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
Pure Virtual Function

● 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.
Pure Virtual Function

Pure Virtual Function


A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have
implementation, we only declare it. A pure virtual function start with virtual keyword and ends with = 0.

Syntax of Pure virtual function :


virtual f() = 0;
Use of Pure Virtual Function

Pure virtual functions are used


● if a function doesn't have any use in the base class
● but the function must be implemented by all its derived classes

Let's take an example,


Suppose, we have derived Car, Bike and Cycle classes from the Vehicle class, and we want to calculate
the Speed of all these Vehicles. In this case, we can create a pure virtual function named
calculateSpeed() in the Vehicle. Since it's a pure virtual function, all derived classes Car, Bike and
Cycle must include the calculateSpeed() function with implementation.
Example

#include <iostream> int main()


using namespace std; {
class Base //abstract class Base *bptr;
{ //Base b;
public: Derived d;
virtual void show() = 0; //pure virtual function bptr = &d;
}; bptr->show();
class Derived : public Base return 0;
{ }
public:
void show()
{
cout << "Derived class is derived from the base class." ;
}
};
Virtual function Pure virtual function

A virtual function is a member function in a base class that can be A pure virtual function is a member function in a base class whose
redefined in a derived class. declaration is provided in a base class and implemented in a
derived class.

The classes which are containing virtual functions are not abstract The classes which are containing pure virtual function are the
classes. abstract classes.

In case of a virtual function, definition of a function is provided In case of a pure virtual function, definition of a function is not
in the base class. provided in the base class.

The base class that contains a virtual function can be instantiated. The base class that contains a pure virtual function becomes an
abstract class, and that cannot be instantiated.

If the derived class will not redefine the virtual function of the If the derived class does not define the pure virtual function; it will
base class, then there will be no effect on the compilation. not throw any error but the derived class becomes an abstract class.

All the derived classes may or may not redefine the virtual All the derived classes must define the pure virtual function.
function.

Difference between Virtual and Pure Virtual Function


Abstract Base Class

Abstract Class is a class which contains at least one Pure Virtual function in it. Abstract classes are
used to provide an Interface for its subclasses.
We cannot create objects of an abstract class.
However, we can derive classes from them, and use their data members and member functions (except
pure virtual functions).
Abstract Base Class: Characteristics

● Abstract class cannot be instantiated, but pointers and references of Abstract class type can be
created.
● Abstract class can have normal functions and variables along with a pure virtual function.
● Abstract classes are mainly used for Up casting, so that its derived classes can use its interface.
● Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will
become Abstract too.
Inheritance
Definition

In C++, inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Advantage of C++ Inheritance

Code reusability: Now you can reuse the members of your parent class. So, there is no need
to define the member again. So less code is required in the class.
Types of Inheritance

● Single inheritance

● Multilevel inheritance

● Multiple inheritance

● Hierarchical inheritance

● Hybrid inheritance
Derived Class
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class <derived_class_name> : <visibility-mode> <base_class_name>


{
// body of the derived class.
}
Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are publicly inherited or privately
inherited. It can be public or private.

base_class_name: It is the name of the base class.


Derived Class

● When the base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class. Therefore, the public members of
the base class are not accessible by the objects of the derived class. It can only be accessible
by the member functions of the derived class.
● When the base class is publicly inherited by the derived class, public members of the base
class also become the public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as well as by the member
functions of the base class.
Single Inheritance

Single inheritance is defined as the Base


inheritance in which a derived class is
inherited from the only one base class.

Derived
When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.

#include <iostream>
int main() {
using namespace std;
Programmer p1;
class Account {
cout<<"Salary: "<<p1.salary<<endl;
public:
cout<<"Bonus: "<<p1.bonus<<endl;
float salary = 60000;
cout<<“Total:”<< p1.salary+ p1.bonus;
};
return 0;
class Programmer : public Account {
}
public: Output:
float bonus = 5000; Salary: 60000
Bonus: 5000
};
Total:65000
Let's see another example of single level inheritance.

#include <iostream> class B : private A


using namespace std; {
class A public:
{ void display()
int a = 4; {
int b = 5; int result = mul();
public: cout <<"Multiplication of a and b is : "<<result<<
std::endl;
int mul()
} };
{
int main()
int c = a*b;
{
return c;
B b;
}
b.display();
};
return 0;
}
How to make a Private Member Inheritable

The private member is not inheritable. If we Visibility modes can be classified into three
categories:
modify the visibility mode by making it
public, but this takes away the advantage of
data hiding.

C++ introduces a third visibility modifier,


i.e., protected. The member which is
declared as protected will be accessible to
all the member functions within the class as
well as the class immediately derived from
it.
Multi Level Inheritance

When one class inherits another class


which is further inherited by another
class, it is known as multi level
inheritance in C++. Inheritance is
transitive so the last derived class
acquires all the members of all its base
classes.
Multi Level Inheritance
#include <iostream> class BabyDog: public Dog
using namespace std; {
class Animal { public:
public: void weep() {
void eat() { cout<<"Weeping...";
cout<<"Eating..."<<endl; }
} };
}; class Dog: public Animal int main(void) {
{ BabyDog d1;
public: d1.eat();
void bark(){ d1.bark(); Output:
cout<<"Barking..."<<endl; d1.weep(); Eating...
Barking...
} return 0; Weeping...
}; }
Example

#include <iostream>
using namespace std;

class base //single base class


{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
};

class derive1 : public base // derived class from base class


{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> y;
}
};
Example

class derive2 : public derive1 // derived from class derive1


{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{ OUTPUT:
cout << "\nProduct= " << x * y * z;
} Enter value of x= 2
};
Enter value of y= 3
int main()
{ Enter value of z= 3
derive2 a; //object of derived class
a.getdata(); Product= 18
a.readdata();
a.indata();
a.product();
return 0;
}
Practice Question
1. Create a class called "Vehicle" with attributes like "make," "model," and "year," and
then create a class called "Car" that inherits from "Vehicle." Add a method to display
the car's details.
2. Create a base class Person with attributes name and age. Then, create a derived class
Employee that inherits from Person and includes additional attributes such as
employee_id and salary. Implement a method to display the details of an employee.
Practice Question
Create a class called "Shape," a subclass called "Circle" that inherits from "Shape," and a
subclass called "Cylinder" that inherits from "Circle." Each class should have relevant
attributes and methods.
VEHICLE

CAR BIKE

FORD AUDI KTM ROYALENFIELD


Multiple Inheritance

Multiple inheritance is the process


of deriving a new class that inherits
the attributes from two or more
classes.
class D : visibility B-1, visibility B-2, ?

// Body of the class;

}
Multiple Inheritance
#include <iostream> class B
using namespace std; {
class A protected:
{ int b;
protected: public:
int a; void get_b(int n)
public: {
void get_a(int n) b = n;
{ }
a = n; };
}
};
Multiple Inheritance
class C : public A, public B int main()
{ {
public: C c;
void display() c.get_a(10);
{ c.get_b(20);
std::cout << "The value of a is : " <<a<< std::endl; c.display();
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b; return 0;
} }
};
Practice Question

Create two classes named Mammals and MarineAnimals. Create another class named BlueWhale
which inherits both the above classes.
Now, create a function in each of these classes which prints "I am mammal", "I am a marine
animal" and "I belong to both the categories: Mammals as well as Marine Animals" respectively.
Now, create an object for each of the above class and try calling

1 - function of Mammals by the object of Mammal


2 - function of MarineAnimal by the object of MarineAnimal
3 - function of BlueWhale by the object of BlueWhale
4 - function of each of its parent by the object of BlueWhale
Practice Question

We want to calculate the total marks of each student of a class in Physics,Chemistry, Mathematics,
English and Computer and the average marks of the class. The number of students in the class are
entered by the user. Create a class named Marks with data members for roll number, name and
marks. Create five other classes inherited by the Marks class, namely Physics, Chemistry,
Mathematics, English and Computer which are used to define marks in individual subject of each
student. Roll number of each student will be generated automatically.
Physics Chemistry Mathematics English Computer

Marks

roll number
name
marks
Ambiguity in Multiple Inheritance

The most obvious problem with multiple inheritance occurs during function overriding.
Suppose, two base classes have a same function which is not overridden in derived class.
If you try to call the function using the object of the derived class, compiler shows error.
It's because compiler doesn't know which function to call. For example,
Ambiguity in Multiple Inheritance

class base1 { This problem can be solved using the scope


public: resolution function to specify which function
void someFunction( ) {....}
to class either base1or base2
};
class base2 {
void someFunction( ) {....}
};
class derived : public base1, public base2 {};

int main() { int main()


derived obj; {
obj.someFunction() // Error! obj.base1::someFunction( ); // Function of base1 class is called
obj.base2::someFunction(); // Function of base2 class is called
} }
Hierarchical Inheritance

If more than one class is inherited from


the base class, it's known as hierarchical
inheritance. In hierarchical inheritance, all
features that are common in child classes
are included in the base class.
Example

// C++ program to demonstrate hierarchical // derived class 2


inheritance class Cat : public Animal {
public:
#include <iostream> void meow() {
using namespace std; cout << "I am a Cat. Meow." << endl;
}
// base class };
class Animal {
public: int main() {
void info() { // Create object of Dog class
cout << "I am an animal." << endl; Dog dog1;
} cout << "Dog Class:" << endl;
}; dog1.info(); // Parent Class function
dog1.bark();
// derived class 1
class Dog : public Animal { // Create object of Cat class
public: Cat cat1;
void bark() { cout << "\nCat Class:" << endl;
cout << "I am a Dog. Woof woof." << endl; cat1.info(); // Parent Class function
} cat1.meow();
};
return 0;
}
Example

#include <iostream> class Triangle : public Shape // inheriting Shape class


using namespace std; {
class Shape // Declaration of base class. public:
{ int triangle_area()
public: {
int a; float result = 0.5*a*b;
int b; return result;
void get_data(int n,int m) }
{ };
a= n;
b = m;
}
};

class Rectangle : public Shape // inheriting Shape class


{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
Example

int main() {
Rectangle r;
Output:
Triangle t;
Enter the length and breadth of a rectangle:
int length,breadth,base,height;
15
cout << "Enter the length and breadth of a rectangle: " <<endl;
10
cin>>length>>breadth;
Area of the rectangle is : 150
r.get_data(length,breadth);
Enter the base and height of the triangle:
int m = r.rect_area();
10
cout << "Area of the rectangle is : " <<m<<endl;
12
cout << "Enter the base and height of the triangle: " <<endl;
Area of the triangle is : 60
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
cout <<"Area of the triangle is : " << n<<endl;
return 0;
}
Hybrid Inheritance

Hybrid inheritance is a combination


of more than one type of inheritance.
Hybrid Inheritance

#include <iostream> class B : public A


using namespace std; {
class A protected:
{ int b;
protected: public:
int a; void get_b()
public: {
void get_a() cout << "Enter the value of 'b' : " <<endl;
{ cin>>b;
cout << "Enter the value of 'a' : " <<endl; }
cin>>a; }; class C
} {
}; protected:
int c;
public:
void get_c()
{
cout << "Enter the value of ‘c’ : " << endl;
cin>>c;
}
};
Hybrid Inheritance

class D : public B, public C Output:


{
Enter the value of ‘a’:10
protected:
Enter the value of ‘a’:5
int d;
public: Enter the value of ‘a’:2
void mul() Multiplication of a,b,c is: 100
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : "
<<a*b*c<<endl;
}
};

int main()
{
D d;
d.mul();
return 0;
}
Diamond Problem

Alternative Names of the Problem

➢ Diamond Problem
➢ Diamond of Death
➢ Disinheritance
➢ Virtual base class
➢ Virtual Inheritance
Base class Default Constructor in Derived class Constructors

When we derive a class from the base class then all the data members of the base class
will become a member of the derived class. We use the constructor to initialize the data
members and here the obvious case is when the data is inherited into the derived class
who will be responsible to initialize them? To initialize the inherited data members
constructor is necessary and that's why the constructor of the base class is called first. In
the program given below, we can see the sequence of execution of constructors in
inheritance is given below:
Constructor Example

#include <iostream> class Derived : public Base int main()


using namespace std; { {
class Base int y; //Base b;
{ Derived d1;
int x; public: Derived d2(10);
// default constructor }
public: Derived()
// default constructor {
Base() cout << "Derived default constructor\n";
{ }
cout << "Base default constructor\n"; // parameterized constructor
} Derived(int i)
}; {
cout << "Derived parameterized constructor\n";
}
};
Example

class Mammals
{
public:
Mammals(){cout<<"Mammals obj created "<<endl;}
void Mammals_statement(){cout<<"I am a mammal. "<<endl;}
};

class Marine_animals
{
public:
Marine_animals(){cout<<"Marine_animals obj created "<<endl;}
void Marine_animals_statement(){cout<<"I am a marine animal. "<<endl;}
};

class Blue_whale: public Mammals, public Marine_animals


{
public:
Blue_whale(){cout<<"Blue_whale obj created "<<endl;}
void Blue_whale_statement(){cout<<"I belong to both the categories: Mammals as well as Marine Animals "<<endl;}
};
Example

int main()
Output:
{

Mammals m1;
m1.Mammals_statement();
cout<<"_______________________________________________"<<endl;
Marine_animals m_a1;
m_a1.Marine_animals_statement();
cout<<"_______________________________________________"<<endl;

Blue_whale bw1;
bw1.Blue_whale_statement();
bw1.Marine_animals_statement();
bw1.Mammals_statement();
cout<<"_______________________________________________"<<endl;

return 0;
}
Base class Parameterized Constructor in Derived class Constructor:

Let's see how we can call the parameterized constructor in the Derived
class, We need to explicitly define the calling for the parameterized
constructor of the derived class using : operator while defining the
parameterized constructor in a derived class.
Constructor Example

#include <iostream> class Derived: public Base


using namespace std; {
class Base int y;
{ public:
int x; // parameterized constructor
public: Derived(int j):Base(j)
// parameterized constructor {
Base(int i) y = j;
{ cout << "Derived Parameterized Constructor\n";
x = i; }
cout << "Base Parameterized Constructor\n"; };
}
}; int main()
{
Derived d(10) ;
}
Here are some basic rules to figure out the Order of Constructor Call with Inheritance
in C++.

● Construction always starts with the base class. If there are multiple base classes
then, construction starts with the leftmost base. If there is a virtual inheritance then
it's given higher preference.
● Then the member fields are constructed. They are initialized in the order they are
declared
● Finally, the class itself is constructed
● The order of the destructor is exactly the reverse

You might also like