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

Unit - 4 CC

The document discusses inheritance in object-oriented programming, explaining its significance and various types such as single, multiple, hierarchical, and hybrid inheritance. It also covers the concepts of polymorphism, including compile-time and runtime polymorphism, as well as pointers and virtual functions in C++. Additionally, it addresses input/output operations in C++ and the stream classes used for these operations.

Uploaded by

PRIYADHARSHINI K
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)
9 views17 pages

Unit - 4 CC

The document discusses inheritance in object-oriented programming, explaining its significance and various types such as single, multiple, hierarchical, and hybrid inheritance. It also covers the concepts of polymorphism, including compile-time and runtime polymorphism, as well as pointers and virtual functions in C++. Additionally, it addresses input/output operations in C++ and the stream classes used for these operations.

Uploaded by

PRIYADHARSHINI K
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 -4

Inheritance :
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Inheritance is a feature or a process in which, new classes are created from the existing
classes. The new class created is called “derived class” or “child class” and the existing class
is known as the “base class” or “parent class”. The derived class now is said to be inherited
from the base class.

When we say derived class inherits the base class, it means, the derived class inherits all
the properties of the base class, without changing the properties of base class and may add
new features to its own. These new features in the derived class will not affect the base
class. The derived class is the specialized class for the base class.

 Sub Class: The class that inherits properties from another class is called Subclass or
Derived Class.
 Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.
The article is divided into the following subtopics:
 Why and when to use inheritance?
 Modes of Inheritance
 Types of Inheritance
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The
methods fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we
create these classes avoiding inheritance then we have to write all of these functions in
each of the three classes as shown below figure:
You can clearly see that the above process results in duplication of the same code 3 times.
This increases the chances of error and data redundancy. To avoid this type of situation,
inheritance is used. If we create a class Vehicle and write these three functions in it and
inherit the rest of the classes from the vehicle class, then we can simply avoid the
duplication of data and increase re-usability. Look at the below diagram in which the three
classes are inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three times as
we have inherited the rest of the three classes from the base class (Vehicle).
Implementing inheritance in C++: For creating a sub-class that is inherited from the base
class we have to follow the below syntax.

Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>

{ //body

Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified, PRIVATE is
taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class declares.
Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }
Modes of Inheritance: There are 3 modes of inheritance.
1. Public Mode: If we derive a subclass from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both
public members and protected members of the base class will become protected in
the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both public
members and protected members of the base class will become Private in the
derived class.
Syntax:

class A {
public:
int x;

protected:
int y;

private:
int z;
};

class B : public A {
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D };

Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Types of Inheritance in C++
1. Single Inheritance : In single inheritance, a class is allowed to inherit from only one
class. i.e. one subclass is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
Example :
#include<iostream>
using namespace std;

class Vehicle {
public: //base class
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
class Car : public Vehicle { // sub class

};
int main()
{
Car obj;
return 0;
}

2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit
from more than one class. i.e one subclass is inherited from more than one base class.

Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....

// body of subclass

};
class B

... .. ...

};

class C

... .. ...

};

class A: public B, public C

... ... ...

};

Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode
for every base class must be specified.

Example :

#include <iostream>

using namespace std;

class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; } // base1
};

class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n"; // base 2
}
};
class Car : public Vehicle, public FourWheeler { // sub class
};
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;
}

Output
This is a Vehicle
This is a 4 wheeler Vehicle

4. Hierarchical Inheritance :
In this type of inheritance, more than one subclass is inherited from a single base class.
i.e. more than one derived class is created from a single base class.

Syntax:-
class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

Example :#include <iostream>


using namespace std;

class Vehicle { // base class

public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

class Car : public Vehicle { // first sub class

};

class Bus : public Vehicle { // second sub class

};
int main()
{
Car obj1;
Bus obj2;
return 0; }
Output
This is a Vehicle This is a Vehicle

6. Hybrid (Virtual) Inheritance : Hybrid Inheritance is implemented by combining more


than one type of inheritance. For example: Combining Hierarchical inheritance and
MultipleInheritance.
Below image shows the combination of hierarchical and multiple inheritances:
#include <iostream>
using namespace std;

class Vehicle { // base class

public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; } // base class

};

class Car : public Vehicle { // first sub class

};

class Bus : public Vehicle, public Fare { // second sub class


};

int main()
{

Bus obj2;
return 0;
}

Output
This is a Vehicle

Fare of Vehicle
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 is a person who at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So the
same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-
Oriented Programming.
Types of Polymorphism
 Compile-time Polymorphism.
 Runtime Polymorphism.

Types of Polymorphism

1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and changing the
type of arguments. In simple terms, it is a feature of object-oriented programming
providing many functions to have the same name but distinct parameters when numerous
tasks are listed under one function name. There are certain Rules of Function
Overloading that should be followed while overloading a function.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic
polymorphism are other names for runtime polymorphism. The function call is resolved at
runtime in runtime polymorphism . In contrast, with compile time polymorphism, the
compiler determines which function call to bind to the object after deducing it at runtime.
A. Function Overriding
Function Overriding 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.

Function overriding Explanation

Pointers

Pointers are symbolic representations of addresses. They enable programs to simulate call-by-
reference as well as to create and manipulate dynamic data structures. Iterating over elements
in arrays or other data structures is one of the main use of pointers.

The address of the variable you’re working with is assigned to the pointer variable that points
to the same data type (such as an int or string).

Syntax:
datatype *var_name;

int *ptr; // ptr can point to an address which holds int data
How to use a pointer?

 Define a pointer variable


 Assigning the address of a variable to a pointer using the unary operator (&) which
returns the address of that variable.
 Accessing the value stored in the address using unary operator (*) which returns the
value of the variable located at the address specified by its operand.
The reason we associate data type with a pointer is that it knows how many bytes the data is
stored in. When we increment a pointer, we increase the pointer by the size of the data type to
which it points.

EXAMPLE : #include <bits/stdc++.h>


using namespace std;
void geeks()
{
int var = 20;
// declare pointer variable
int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


cout << "Value at ptr = " << ptr << "\n";
cout << "Value at var = " << var << "\n";
cout << "Value at *ptr = " << *ptr << "\n";
}
// Driver program
int main()
{
geeks();
return 0;
}

Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20

VIRTUAL FUNCTION

A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. 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 function.

 Virtual functions ensure that the correct function is called for an object, regardless
of the type of reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at runtime.
Rules for Virtual Functions
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base class type to
achieve runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as derived
class.
5. They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in
that case, the base class version of the function is used.
6. A class may have virtual destructor but it cannot have a virtual constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions

EXAMPLE:
#include<iostream>
using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class\n";
}

void show()
{
cout << "show base class\n";
} };

class derived : public base {


public:
void print()
{
cout << "print derived class\n";
}

void show()
{
cout << "show derived class\n";
} };
int main()
{
base *bptr;
derived d;
bptr = &d;
bptr->print(); // Virtual function, binded at runtime

bptr->show(); // Non-virtual function, binded at compile time


return 0;
}
Output:
print derived class show base class
CONSOLE INPUT/OUTPUT OPERATION IN C++

Every program takes some data as input and generates processed data as an output
following the familiar input process output cycle. It is essential to know how to provide the
input data and present the results in the desired form. The use of the cin and cout is
already known with the operator >> and << for the input and output operations. In this
article, we will discuss how to control the way the output is printed.
C++ supports a rich set of I/O functions and operations. These functions use the
advanced features of C++ such as classes, derived classes, and virtual functions. It also
supports all of C’s set of I/O functions and therefore can be used in C++ programs, but their
use should be restrained due to two reasons.
1. I/O methods in C++ support the concept of OOPs.
2. I/O methods in C cannot handle the user-define data type such as class and object.
It uses the concept of stream and stream classes to implement its I/O operations with the
console and disk files.
C++ Stream
The I/O system in C++ is designed to work with a wide variety of devices including
terminals, disks, and tape drives. Although each device is very different, the I/O system
supplies an interface to the programmer that is independent of the actual device being
accessed. This interface is known as the stream.
 A stream is a sequence of bytes.
 The source stream that provides the data to the program is called the input stream.
 The destination stream that receives output from the program is called the output
stream.
 The data in the input stream can come from the keyboard or any other input device.
 The data in the output stream can go to the screen or any other output device.
C++ contains several pre-defined streams that are automatically opened when a program
begins its execution. These include cin and cout. It is known that cin represents the input
stream connected to the standard input device (usually the keyboard) and cout represents
the output stream connected to the standard output device (usually the screen).

C++ Stream Classes


The C++ I/O system contains a hierarchy of classes that are used to define various
streams to deal with both the console and disk files. These classes are called stream
classes. The hierarchy of stream classes used for input and output operations is with the
console unit. These classes are declared in the header file iostream. This file should be
included in all the programs that communicate with the console unit.

#include <iostream>
using namespace std;
int main()
{

cout << " This is my first"


" Blog on the gfg";
return 0; }
Output:
This is my first Blog on the gfg

The ios are the base class for istream (input stream) and ostream (output stream) which
are in turn base classes for iostream (input/output stream). The class ios are declared as
the virtual base class so that only one copy of its members is inherited by the iostream.
The class ios provide the basics support for formatted and unformatted I/O operations . The
class istream provides the facilities formatted and unformatted input while the class
ostream (through inheritance) provides the facilities for formatted output.
The class iostream provides the facilities for handling both input and output streams. Three
classes add an assignment to these classes:

 istream_withassign
 ostream_withassign
 iostream_withassign

Class name content


 Contains basic facilities that are used by all other input
and output classes
 Also contains a pointer to a buffer object
ios (General (streambuf object)
input/output stream  Declares Constants and functions that are necessary for
class) handling formatted input and output operations

 It inherits the properties of ios


 It declares input functions such as get(), getline(), and
istream (Input read()
stream)  It contains overload extraction operator >>

 It inherits the properties of ios.


ostream (Output  It declares input functions such as put() and write().
Stream)  It contains an overload extraction operator <<.

iostream  Inherits the properties of ios


(Input/output stream and ostream through multiple inheritances and
stream) thus contains all the input and output functions.

 It provides an interface to physical devices through


buffers.
Streambuf  It acts as a base for filebuf class used ios file.

You might also like