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

ProgInC++(Unit-3)

Uploaded by

grksr10112005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

ProgInC++(Unit-3)

Uploaded by

grksr10112005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit-3

C++ Inheritance

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.

A Derived class is defined as the class derived from the base class.

The Syntax of Derived class: (OR) Syntax of Inheritance

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.

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 (or) Class Hierarchies

C++ supports five types of inheritance:Difference between JDK, JRE, and JVM
 Single inheritance
 Multiple inheritance
 Hierarchical inheritance
 Multilevel inheritance
 Hybrid inheritance

1
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.

Where 'A' is the base class, and 'B' is the derived class.

//Program to Demonstrate Single Level Inheritance


#include <iostream>
using namespace std;
class Account //Base Class
{
public:
float salary = 60000;
};
class Programmer: public Account //Derived Class
{
public:
float bonus = 5000;
};
int main()
{
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;

2
return 0;
}

Multilevel Inheritance

Multilevel inheritance is a process of deriving a class from another derived class. 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 acquire all the members of all its base classes.

//Program to Demonstrate Multi Level Inheritance

#include<iostream>
using namespace std;
class stu
{
int rno;
char name[15];
public:
void gets()
{
cout<<"enter rollno and name:";
cin>>rno>>name;
cout<<"rollno="<<rno<<endl;
cout<<"name="<<name<<endl;
}
};
class marks:public stu
{
protected:
int m,p,c;
public:
void getm()
{
cout<<"enter m,p,c marks:";
cin>>m>>p>>c;
cout<<m<<" "<<p<<" "<<c<<endl;

3
}
};
class result:public marks
{
int total,avg;
public:
void getr()
{
total=m+p+c;
avg=total/3;
cout<<"total="<<total<<endl;
cout<<"average="<<avg;
}
};
int main()
{
result r;
r.gets();
r.getm();
r.getr();
return 0;

}
Multiple Inheritance

Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more
classes.

Syntax of the Derived class:

class D : visibility B-1, visibility B-2…


{
// Body of the class;
}

//program to demonstrate multiple inheritance

#include<iostream>
using namespace std;

4
#include<conio.h>
class stu
{
int rno;
char name[15];
public:
void gets()
{
cout<<"enter rollno and name:";
cin>>rno>>name;
cout<<"rollno="<<rno;
cout<<"name="<<name;
}
};
class marks
{
protected:
int m,p,c;
public:
void getm()
{
cout<<"enter m,p,c marks:";
cin>>m>>p>>c;
cout<<m<<" "<<p<<" "<<c<<endl;
}
};
class result:public stu,public marks
{
int total,avg;
public:
void getr()
{
total=m+p+c;
avg=total/3;
cout<<"total="<<total<<endl;
cout<<"average="<<avg;
}
};
int main()
{
result r;
r.gets();
r.getm();
r.getr();
return 0;

5
Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one class from a base class.

Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

Visibility modes (OR) Base class Access Specifications

Visibility mode defines the scope of members of base class into derived class.

Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible by its own class, derived class and
in main function.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as
well as the class immediately derived from it.

Visibility of Inherited Members

6
Base class visibility Derived class visibility

Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

Constructor and Destructor in Inheritance


Whenever we create an object of a class, the default constructor of that class is invoked automatically
to initialize the members of the class.
If we inherit a class from another class and create an object of the derived class, it is clear that the
default constructor of the derived class will be invoked but before that the default constructor of all
of the base classes will be invoke, i.e the order of invocation is that the base class’s default
constructor will be invoked first and then the derived class’s default constructor will be invoked.
Why the base class’s constructor is called on creating an object of derived class?
The data members and member functions of base class comes automatically in derived class based on
the access specifier but the definition of these members exists in base class only. So when we create
an object of derived class, all of the members of derived class must be initialized but the inherited
members in derived class can only be initialized by the base class’s constructor as the definition of
these members exists in base class only. This is why the constructor of base class is called first to
initialize all the inherited members.
Destructors in C++ are called in the opposite order of that of Constructors.

// C++ program to show the order of constructor call


// in single inheritance

#include <iostream>
using namespace std;

// base class
class Parent
{
public:

// base class constructor


Parent()
{
cout << "Inside base class" << endl;
}

7
};

// sub class
class Child : public Parent
{
public:

//sub class constructor


Child()
{
cout << "Inside sub class" << endl;
}
};

// main function
int main() {

// creating object of sub class


Child obj;

return 0;
}

Output:
Inside base class
Inside sub class
Order of constructor and Destructor call for a given order of Inheritance

Redefining Base Class Function (Function Overriding)

If derived class defines same function as defined in its base class, it is known as function overriding in C+
+. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of the
function which is already provided by its base class.

(OR)

8
Function Overriding (achieved at run time)
It is the redefinition of base class function in its derived class with same signature i.e return type and
parameters. It can only be done in derived class.
Example:
class a
{
public:
void display()
{
cout << "hello";
}
};

class b:public a
{
public:
void display()
{
cout << "bye";
}
};
int main()
{
b b1;
b1.display();
return 0;
}
Function Overloading VS Function Overriding:
1. Inheritance: Overriding of functions occurs when one class is inherited from another class.
Overloading can occur without inheritance.
2. Function Signature: Overloaded functions must differ in function signature ie either number of
parameters or type of parameters should differ. In overriding, function signatures must be same.
3. Scope of functions: Overridden functions are in different scopes; whereas overloaded functions
are in same scope.
4. Behavior of functions: Overriding is needed when derived class function has to do some added or
different job than the base class function. Overloading is used to have same name functions which
behave differently depending upon parameters passed to them.
Polymorphism
The word polymorphism means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form. A real-life example of polymorphism, a
person at the same time can have different characteristics. Like a man at the same time is a father, a
husband, an employee. So the same person posses different behavior in different situations. This is
called polymorphism. Polymorphism is considered as one of the important features of Object Oriented
Programming.
In C++ polymorphism is mainly divided into two types:
1. Compile time Polymorphism
2. Runtime Polymorphism

9
1. Compile time polymorphism: This type of polymorphism is achieved by function overloading or
operator overloading.
 Function Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded
by change in number of arguments or/and change in type of arguments.
// C++ program for function overloading
#include <iostream>
using namespace std;
class sample
{
public:

// function with 1 int parameter


void func(int x)
{
cout << "value of x is " << x << endl;
}

// function with same name but 1 double parameter


void func(double x)
{
cout << "value of x is " << x << endl;
}

// function with same name and 2 int parameters


void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

int main() {

sample obj1;

// Which function is called will depend on the parameters passed


// The first 'func' is called

10
obj1.func(7);

// The second 'func' is called


obj1.func(9.132);

// The third 'func' is called


obj1.func(85,64);
return 0;
}

2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.


 Function overriding on the other hand occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
Example:
#include<iostream>
using namespace std;
class a
{
public:
void display()
{
cout << "hello";
}
};

class b:public a
{
public:
void display()
{
cout << "bye";
}
};
int main()
{
b b1;
b1.display();
return 0;
}

Virtual Function in C++


o 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.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.

11
o 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.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o 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.

Late binding or Dynamic linkage

In late binding function call is resolved during runtime. Therefore compiler determines the type of object
at runtime, and then binds the function call.

Rules of Virtual Function

o Virtual functions must be members of some class.


o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o 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.
o We cannot have a virtual constructor, but we can have a virtual destructor
o Consider the situation when we don't use the virtual keyword.

#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;

12
} };
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}

Output:

Value of x is : 5

In the above example, * a is the base class pointer. The pointer can only access the base class members
but not the members of the derived class. Although C++ permits the base pointer to point to any object
derived from the base class, it cannot directly access the members of the derived class. Therefore, there
is a need for virtual function which allows the base pointer to access the members of the derived class.

C++ virtual function Example

Simple example of C++ virtual function used to invoked the derived class in a program.

#include <iostream>
class A
{
public:
virtual void display()
{

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

Output:

Derived Class is invoked

Pure Virtual Function

o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o 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.
o 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.
o 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 can be defined as:

14
virtual void display() = 0;

Example:

#include <iostream>

using namespace std;


class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{ Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}

Output:

Derived class is derived from the base class.

In the above example, the base class contains the pure virtual function. Therefore, the base class is an
abstract base class. We cannot create the object of the base class.

C++ Abstract class

15
In C++ class is made abstract by declaring at least one of its functions as pure virtual function. A pure
virtual function is specified by placing "= 0" in its declaration. Its implementation must be provided by
derived classes.

#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Rectangle : Shape
{
public:
void draw()
{
cout < <"drawing rectangle..." < <endl;
}
};
class Circle : Shape
{
public:
void draw()
{
cout <<"drawing circle..." < <endl;
}
};
int main( ) {
Rectangle rec;
Circle cir;
rec.draw();
cir.draw();
return 0;
}

Output:

16
drawing rectangle...
drawing circle...

17

You might also like