You are on page 1of 14

Unit 4 - Inheritance in C++

Definition
The capability of a class derives properties and characteristics from another class are
called Inheritance. 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”.
 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
Super class.

Defining Derived Classes


Class derived_class name : access specifiers base_class name
{
//member variables of new class (derivedclass)
}
The names of the derived and base classes are separated by a colon :.
The access specifiers may be private, public or protected.
Types Of Inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

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 :
class X
{
... .. ...
};
class Y: public X
{
... .. ...
};

2. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.

Example

class X
{
... .. ...
};
class Y:public X
{
... .. ...
};
class Z: public Y
{
... ... ...
};

3. 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
};

Example:

class X
{
... .. ...
};
class Y
{
... .. ...
};
class Z: public X, public Y
{
... ... ...
};
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.
Example:

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.
}

5. Hybrid (Virtual) Inheritance:


Hybrid Inheritance is implemented by combining more than one type of inheritance.
For example: Combining Hierarchical inheritance and Multiple Inheritance.
C++ 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.

Syntax:

datatype *var_name;
int *ptr; // ptr can point to an address which holds int data

Example

#include <iostream.h>
using namespace std;
void geeks()
{
int var = 20;
int* ptr;
ptr = &var;
cout <<"Value at ptr = "<< ptr <<"\n";
cout <<"Value at var = "<< var <<"\n";
cout <<"Value at *ptr = "<< *ptr <<"\n";
}
int main()
{
geeks();
return 0; }
Polymorphism

The word “polymorphism” means having many forms.

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.

Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

Managing Console I/O Operations

C++ Stream

The I/O system in C++ 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.

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.
These classes are declared in the header file iostream. This file should be included in all the
programs that communicate with the console unit.

Unformatted data

 The printed data with default setting by the I/O function of the language is known
as unformatted data.

Formatted data

 If the user needs to display a number in hexadecimal format, the data is represented with
the manipulators are known as formatted data.

Input/Output Streams

 The cin and cout are pre-defined streams for input and output data.
Syntax:
cin>>variable_name;
cout<<variable_name;

 The cin object uses extraction operator (>>) before a variable name while
the cout object uses insertion operator (<<) before a variable name.

 The cin object is used to read the data through the input device like keyboard etc. while
the cout object is used to perform console write operation.

Formatted console input/output functions in C++

Example

Functions Description

Using this function, we can specify the width of a


width(int width)
value to be displayed in the output at the console.

Using this function, we can fill the unused white


fill(char ch) spaces in a value(to be printed at the console), with
a character of our choice.
setf(arg1, arg2) Using this function, we can set the flags, which
allow us to display a value in a particular format.

Managing Output with Manipulators


The header file iomanip provides a set of functions called manipulators which can be used to the
manipulate the output formats.
The important manipulators defined by the header IOStream library

endl: It is defined in header ostream. It is used for enter a new line and end1 after entering a new
line it flushes the output stream.
ws: It is defined in header istream and is used for ignore the whitespaces in the string
sequence.

ends: It is also defined in header ostream and it add a null character into the output stream. It
works with std::ostrstream, whenever the output buffer needs to be null character-
terminated to be processed as a C string.

flush: It is also defined in header ostream and this flushes the output stream, i.e. this forces all
the output written on the screen. And without flush, the output would be the same, but
may be not appear in real-time.
Unit 5 Working with Files

Definition

A file is collection of data or information that has a name, called the filename. Files are
stored in secondary storage devices such as floppy disks and hard disks.

FileStreamClasses

A Stream is nothing but a flow of data. In the Object oriented programming the streams
are controlled using the classes.

Details of File Stream Classes:

Class Description
filebuf Sets the file buffers to read and write. It holds constant openprot used in
function open() and close() as a member.
fstreambase The fstreambase acts as a base class for fstream, ifstream, and ofstream.
The functions such as open() and close() are defined in fstreambase
Provides input operations on files. Contains open() with default input
ifstream mode. Inherits the functions as get(), getline(), seekg(), tellg(), and read()
from istream class
Provides output operations on files. Contains open() with default output
ofstream mode. Inherits the functions as put(), seekp(), write(), and
tellp()from ostream class
fstream Provides support for simultaneous input/output file stream class. Inherits
all functions from istream and ostream classes through iostream.
Steps of File Operations

Before performing file operations, it is necessary to create a file. The operation of a file involves
the following basic activities:

 Specifying suitable file name


 Opening the file in desired mode
 Reading or writing the file (file processing)
 Detecting errors
 Closing the file
FileOpening:

In order to perform operations, we have to create file stream object and connecting it
with the file name. The classes ifstream, ofstream, and fstream can be used for creating a
file stream.

Examples:

a) ofstream out (“text”);


b) ifstream in(“list”);

In the statement (a), out is an object of the class ofstream; file name text is opened, and data can
be written to this file. Similarly, in the statement (b), in is an object of the class ifstream.

Program to open an output file using fstream class

#include<iostream>
#include<fstream>
using namespace std
int main()
{
Char name[15];
Int age;
ofstreamout("text");
cout<<"EnterName:"<<endl;
cin>>name;
cout<<"EnterAge:"<<endl;
cin>>age;
cout<<name<<"\t";
cout<<age <<endl;
out.close();
return0;
}

Explanation:
In the above program the statement of streamout(“text”) text is opened and connected
with the object out.

Program to read data from file using object of ifstream class

#include<iostream>
#include<fstream>
Using namespace std;
int main()
{
string name;
int age;
ifstreamin("text");
Opens a file in read mode
inf>>name;
inf>>age;cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age;
inf.close();
return0;
}
Finding End of File

1. While reading data from a file, it is necessary to find where the file ends, that is, the end
of the file.
2. when the end of the file is detected, the process of reading data can be easily terminated.
The eof() member function() is used for this purpose.
3. The eof() stands for the end of the file. It is an instruction given to the program by the
operating system that the end of the file is reached.

Error Handling Functions

1. A file which we are ateempting to open for reading does not exist
2. The file name used for a new file may already exist
3. We may attempt an invalid operation such as reading past the end-of-file
4. There may not be any space in the disk for storing more data
5. We may use an invalid file name
6. We may attempt to perform an operation when the file is not opened for the
purpose.

Error Trapping Functions

Functions Return value and meaning

fail() Returns true when an input or output operations has failed

eof() Returns true (non-zero value) if end-of-file is encountered while reading.


Otherwise returns zero.

bad() Returns true if an invalid operation is attempted or any unrecoverable error


has occurred.

good() Returns true if no error has occurred.


FILE OPENING MODES

The opening of the file also involves several modes depending on the operation to be carried out
with the file. The open() function has the following two arguments:
object.open ( “file_ name”, mode);

File modes

Parameter Operation
ios::app Append to End-of-file
ios::ate Go to end-of-file on opening
ios:: binary Binary file
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exist
ios::out Open file for writing only
ios::trunc Delete the contents of the file if it exists

COMMAND-LINE ARGUMENTS

An executable program that performs a specific task for the operating system is called a
command. The commands are issued from the command prompt of the operating system

The main() function can receive two arguments, they are


(1) argc (argument counter) and
(2) argv (argument vector).
The first argument contains the number of arguments
The second argument is an array of char pointers.
The *argv points to the command-line arguments.
The size of the array is equal to the value counted by the argc.
1. Argument argc: The argument argc counts the total number of arguments passed from
command prompt. It returns a value that is equal to the total number of
arguments passed through the main().
2. Argument argv: It is a pointer to an array of character strings that contains names of
arguments. Each word is an argument.

Syntax - main( int argc, char * argv[]);

Example Programme
#include <iostream>
using namespace std;

int main(int argc, char* argv[])


{
cout <<"You have entered "<< argc <<" arguments:"<< endl;
int i = 0;
while (i < argc)
{
cout <<"Argument "<< i + 1 <<": "<< argv[i] << endl;
i++;
}
return 0;
}
Input
./program1 hello geeks

Output
You have entered 3 arguments:
Argument 1: ./program1
Argument 2: hello
Argument 3: geeks

You might also like