0% found this document useful (0 votes)
27 views

What Is Access Control in Inheritance.: Base Class

Inheritance is a mechanism where one class inherits properties from another class called the base class. The class that inherits is called the derived class. The derived class inherits general traits from the base class and adds specific properties. There are different types of inheritance like public, private, protected that determine how elements of the base class are inherited by the derived class. Pointer is a variable that stores the memory address of another variable. Pointers allow accessing and manipulating variables in memory. Pointer arithmetic and operators like increment, decrement allow manipulating pointers.

Uploaded by

Aarthi E
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

What Is Access Control in Inheritance.: Base Class

Inheritance is a mechanism where one class inherits properties from another class called the base class. The class that inherits is called the derived class. The derived class inherits general traits from the base class and adds specific properties. There are different types of inheritance like public, private, protected that determine how elements of the base class are inherited by the derived class. Pointer is a variable that stores the memory address of another variable. Pointers allow accessing and manipulating variables in memory. Pointer arithmetic and operators like increment, decrement allow manipulating pointers.

Uploaded by

Aarthi E
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Define Inheritance

Inheritance is the mechanism by which one class can inherit the properties of
another. When one class is inherited by another, the class that is inherited is
called the base class. The inheriting class is called the derived class. In general,
the process of inheritance begins with the definition of a base class. The base
class defines all qualities that will be common to any derived class, represent the
most general description of a set of traits. The derived class inherits those
general traits and adds properties that are specific to that class. When one class
inherits another, it uses this general form:

class derived-class-name : access specifier base-class-name{ // ... }

Base Class

Derived Class

What is access control in inheritance.

Here access specifier is the way of inheriting base class properties by the derived
class. The access specifier /type of inheritance are : public, private, or protected.
This determines how elements of the base class are inherited by the derived
class. If access specifier is not mentioned , it takes private inheritance by default.

Access public protected private

Same class yes yes yes

Derived yes yes no


classes

Outside yes no no
classes
Visibility mode/ Access control in Inheritance

The scope of inheritance of the data members and member functions from the
base class to the derived class is called visibility mode
.A derived class can access all the non-private members of its base class. Thus
base-class members that should not be accessible to the member functions of
derived classes should be declared private in the base class.

Visiblity mode and types of inheritance

When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is
specified by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is
commonly used. While using different type of inheritance, following rules are
applied −
• Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the
derived class and protected members of the base class
become protected members of the derived class. A base
class's private members are never accessible directly from a derived class,
but can be accessed through calls to the public and protected members of
the base class.
• Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
• Private Inheritance − When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.
We can summarize the different access types according to – the access
specifier
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;}

o/p : 35

Types of Inheritance

Single Inheritance: It is the inheritance hierarchy wherein one derived


class inherits from one base class.

class base_class
{

};
class derived_ class : visibility-mode base_ class
{
}

Multiple Inheritance:
The process in which a derived class inherits traits from several base classes, is
called multiple inheritance. In Multiple inheritance, there is only one derived
class and several base classes. We declare the base classes and derived class as
given below:
class base_class1
{

};
class base_class2
{

}
Class derived_ class : visibility-mode base_ class1, visibility-mode base_ class2
{

};

Hierarchical Inheritance:
The process in which traits of one class can be inherited by more than one class
is known as Hierarchical inheritance. The base class will include all the features
that are common to the derived classes. A derived classcan serve as a base class
for lower level classes and so on.
class base
{

};
class derived1 : visibility-mode base
{

}
Class derived2 : visibility-mode base
{

};
.
Multilevel Inheritance: he process in which a derived class inherits traits from
another derived class, is called Multilevel Inheritance. A derived class with
multilevel inheritance is declared as :
class base_class
{

};
class derived_ class1 : visibility-mode base_ class
{

};
class derived_ class 2: visibility-mode derived_ class1
{

};
Here, derived_ class 2 inherits traits from derived_ class 1 which itself inherits
from base_class..

Hybrid Inheritance: The inheritance hierarchy that reflects any legal


combination of above four types of inheritance.
POINTERS

Address-of operator (&)

The address of a variable can be obtained by preceding the name of a variable


with an ampersand sign (&), known as address-of operator.

For example: adr = &myvar;

Define Pointer.

A pointer is a variable that stores the memory location of another variable.The


ampersand symbol (&) called the reference operator, the asterisk symbol (*) is
called the dereference operator used while defining a pointer. We use the
reference operator to access the memory address of a variable. For example, if x
contains the address of y, then x is said to “point to” y.

The general form of a pointer variable declaration is

type *var-name;

Here, type is the pointer’s base type. The base type determines what type of data
the pointer will be pointing to.

var-name is the name of the pointer variable

Eg : int *p1; // Here p is a pointer to an integer.

why we use pointers in C++:


1. We can easily access the memory location of any variable directly and
manipulate it according to our convenience.
2. It facilitates the concept of dynamic memory allocation, making it a much
faster language as compared to programming languages that do not support
the use of pointers like Python and Java.
3. We prefer pointers in certain situations to improve the efficiency of certain
procedures

How to use pointer:


Define a pointer variable.
Assign the address of a variable to a pointer
Finally access the value at the address available in the pointer variable.
Example: int var =10;//normal variable
int *ptr; //declare pointer
ptr = &var; //Assign the address of a variable “var” to a pointer ”ptr”
cout<<”var=”<<*p; //prints var=10

Pointer Expressions and Pointer Arithmetic


A limited set of arithmetic operations can be performed on pointers which are:
• incremented ( ++ )
• decremented ( — )
• an integer may be added to a pointer ( + or += )
• an integer may be subtracted from a pointer ( – or -= )
• difference between two pointers (p1-p2) is an integer
• The unary operators ++ and -- (pre- and post-fix versions of each)

int a[]={10,20,30};
int *p;
p=a;
// Pointer moves to the next int position (as if it was an array)
Cout<<p++; //output is 10,display and increments the address
// Pointer moves to the next int position (as if it was an array)
Cout<<++p; //output is 30, increments the address and display

/* All the following three cases are same they increment the value
* of variable that the pointer p points.
*/
Cout<<++*p; //output is 31
Cout<<++(*p); //output is 32
Cout<<++*(p); //output is 33
Void Pointers
This is a special type of pointer available in C++ which represents absence of
type. void pointers are pointers that point to a value that has no type (and thus
also an undetermined length and undetermined dereferencing properties).
This means that void pointers have great flexibility as it can point to any data
type.
Example : void *ptr;
NULL Pointers
Null pointer is a pointer which point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;

int *ptr1 = 0;

int *ptr2 = NULL;

Pointers to pointers
C++ allows the use of pointers that point to pointers, that these, in its turn, point
to data (or even to other pointers). The syntax simply requires an asterisk (*) for
each level of indirection in the declaration of the pointer:
char a;
char * b;
a = 'z';
char ** c;
b = &a;
c = &b;

This, assuming the randomly chosen memory locations for each variable of 7230,
8092, and 10502, could be represented as:

new operator
The new operator requests for the memory allocation in heap. If the sufficient
memory is available, it initializes the memory to the pointer variable and returns
its address.
Here is the syntax of new operator in C++ language,
pointer_variable = new datatype;
int *ptr1 = NULL;
ptr1 = new int;
Delete Operator
The delete operator is used to deallocate the memory. User has privilege to
deallocate the created pointer variable by this delete operator.
Here is the syntax of delete operator in C++ language,

delete pointer_variable;
delete ptr1
this pointer
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member
functions. this pointer holds the address of current object, this pointer points to
the current object of the class. Friend functions do not have a this pointer,
because friends are not members of a class. Only member functions have
a this pointer.

include <iostream>

using namespace std;

class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}

return 0;
}
When the above code is compiled and executed, it produces the following result −

Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
POLYMORPHISM
Polymorphism in C++ is basically the ability for data to be processed or
represented in more than one form. Typically, polymorphism occurs when there is
a hierarchy of classes and they are related by inheritance.
Polymorphism allows the data in the form of a message or a group of statements
when executed to behave differently in different scenarios.

Types of Polymorphism in C++


Polymorphism in C++ can be classified into two types:

1. Compile-time polymorphism: We can achieve this type of polymorphism


only during compilation. We can implement this type of polymorphism
through function overloading and operator overloading, an exclusive feature
of C++. Since function overloading and operator overloading is based on the
type and number of the parameter passed, the compiler chooses the
appropriate function call at compile-time.
2. Runtime polymorphism: We can achieve this type of polymorphism only
during the runtime of the program. It is also known as function overriding,
dynamic binding, and late binding. In order to achieve runtime
polymorphism, we use the concept of virtual functions which is based on
pointers. In contrast to compile-time polymorphism, it is a tad slower but
proves to be more flexible.

Function Overriding

Function overriding is a feature that allows us to have a same function both in


child class and also in the parent class. A child class override a functionality of
the parent class then it is function overriding. It is like creating a new version of
an old function, in the child class.

To call the overridden function by using the object of child class. You can do that
by creating the child class object in such a way that the reference of parent class
points to it.
Eg.

include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
/* Reference of base class pointing to
* the object of child class.
*/
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}

Difference between function overloading and function overriding

1) Function Overloading happens in the same class when we declare same


functions with different arguments in the same class. Function Overriding
is happens in the child class when child class overrides parent class
function.

2) In function overloading function signature should be different for all the


overloaded functions. In function overriding the signature of both the
functions (overriding function and overridden function) should be same

3) Overloading happens at the compile time thats why it is also known as


compile time polymorphism while overriding happens at run time which is
why it is known as run time polymorphism.

4) 4) In function overloading we can have any number of overloaded functions.


In function overriding we can have only one overriding function in the child
class.
What is late binding or dynamic binding
When the selection of the function to be called at any given point in the program
to be based on the kind of object for which it is called during runtime. This sort
of operation is referred to as dynamic linkage, or late binding

Virtual functions in C++ - Runtime Polymorphism

what are virtual functions and why we use them


A virtual function is a function in a base class that is declared using the keyword
virtual. Defining in a base class a virtual function, with another version in a
derived class, signals to the compiler that we don't want static linkage for this
function. It uses dynamic binding.
. When we declare a function as virtual in a class, all the sub classes that
override this function have their function implementation as virtual by default
(whether they mark them virtual or not).

Why we declare a function virtual?


To let compiler know that the call to this function needs to be resolved at
runtime (also known as late binding and dynamic linking) so that the object type
is determined and the correct version of the function is called. The virtual
functions implements runtime polymorphism.

#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound(){
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Pure Virtual Functions:
It's possible that you'd want to include a virtual function in a base class so that
it may be redefined in a derived class to suit the objects of that class, but that
there is no meaningful definition you could give for the function in the base
class. The pure virtual function is a function that has the notation "= 0" in
the declaration of that function.
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound()=0
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}

Abstract class
When a class contains atleast one pure virtual function, it is referred to as an
abstract class. Since, an abstract class contains atleast one function for which
nobody exists, it is, technically, an incomplete type, and no objects of that class
can be created. Thus, abstract classes exist only to be inherited. We can still
create a pointer to an abstract class,
Unit – V

File Handling in c++


File.
The information / data stored under a specific name on a storage
device, is called a file.

Stream.
It refers to a sequence of bytes. The C++ I/O system operates through streams. A
stream is logical device that either produces or consumes information. A stream
is linked to a physical device by the C++ I/O system.
Two types of streams:
Output stream: a stream that takes data from the program and sends (writes) it
to destination.
Input stream: a stream that extracts(reads) data from the source and sends it to
the program.

Types of files
Text file. It is a file that stores information in ASCII characters. In text files,
each line of text is terminated with a special character known as EOL (End of
Line) character or delimiter character. When this EOL character is read or
written, certain internal translations take place. It has extension as “.txt”
Binary file. It is a file that contains information in the same format as it is
held in memory. In binary files, no delimiters are used for a line and no
translations occur here. This has extension as “.dat”.

Classes for file stream operation


To perform file I/O, you must include <fstream> Inyour program. It defines
several classes, including ifstream, ofstream and fstream. In C++, a file is opened
by linking it to a stream. There are three types of streams, before you can open a
file, you must first obtain a stream.
ofstream: Stream class to write on files. Its member function open( ) associates the stream with a
specified file in an output mode. In addition to open(), ofstream inherits the following functions from ostream class
(i) put( ) (ii) write( ) (iii) seekp( ), (iv) tellp
ifstream: Stream class to read from files.Its member function open( ) associates the stream with a
specified file in an input mode. In addition to open(), ifstream class inherits the following functions from istream class.
(i) get( ) (ii) getline( ) (iii) read( ) (iv) seekg( ) (iv) tellg( )
fstream: Stream class to both read and write from/to files. It supports files for simultaneous
input and output. It is derived from ifstream, ofstream and iostream classes.
The functions associated with this stream are :
1. open : This associates the stream with a specified file.
2. close : It closes the stream.
3. close all : It closes all the opened streams
4. seekg : Sets current `get' position in a stream
5. seekp : Sets current `put' position in a stream
6. tellg : Returns the current `get' position in a stream
7. tellp : Returns the current `put' position in a stream.
Operations in File Handling:

• Creating a file: open()


• Reading data: read()
• Writing new data: write()
• Closing a file: close()

Opening a file
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may
be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and
ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open() member function defines the mode in which the file should be opened.
Two methods of opening a file.
OPENING FILE USING CONSTRUCTOR
ofstream fout(“results”); //output only
ifstream fin(“data”); //input only

OPENING FILE USING open()


Stream-object.open(“filename”, mode)
ofstream ofile;
ofile.open(“data1”);
ifstream ifile;
ifile.open(“data2”);

Closing File
When we are finished with our input and output operations on a file we shall close it. Then call the stream's
member function close. This member function takes flushes the associated buffers and closes the file:
fout.close();
fin.close();

File Modes:
File modes specify that, how file data will be read and write operation perform.
Mode
1. ios::in Open file for read only mode.
2. ios::out Open file for writing mode.
3. ios::app Append data to the end of file.
4. ios::ate Write data on the end of file and provide the
facility of modifying existing contents.
5. ios::binary Create the binary file.
6. ios::nocreate Open fail if file does not exist.
7. ios::noreplace Open fail if file already exist.
8. ios::trunc Delete all the contents of the file if it exists. It
will not create new file.
INPUT AND OUTPUT OPERATION
put() and get() function
the function put() writes a single character to the associated stream. Similarly,
the function get() reads a single character form the associated stream.
example :
file.get(ch);
file.put(ch);

write() and read() function


write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));

ERROR HANDLING FUNCTION


FUNCTION RETURN VALUE AND MEANING
eof()
returns true (non zero) if end of file is encountered while
reading; otherwise return false(zero)
fail() return true when an input or output operation has failed
bad()
returns true if an invalid operation is attempted or any
unrecoverable error has occurred.
good() returns true if no error has occurred.

File Pointers And Their Manipulation


All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that points to the
element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that points to the
location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from iostream
(which is itself derived from both istream and ostream).
These internal stream pointers that point to the reading or writing locations
within a stream can be manipulated using the following member functions:
seekg() moves get pointer(input) to a specified location
seekp() moves put pointer (output) to a specified location
tellg() gives the current position of the get pointer
tellp() gives the current position of the put pointer
The other prototype for these functions is:
seekg(offset, refposition );
seekp(offset, refposition );
The parameter offset represents the number of bytes the file pointer is to be
moved from the
location specified by the parameter refposition. The refposition takes one of the
following three
constants defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
example:
file.seekg(-10, ios::cur);

File I/O is a five-step process:


1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other input/output functions.(Read, write, read and write)
5. Close the files.

#Program to create and write into a text file


#include <fstream>
using namespace std;

int main()
{
ofstream fout;
fout.open("out.txt");

char str[300] = "Time is a great teacher but


unfortunately it kills all its pupils. Berlioz";

//Write string to the file.


fout << str;

fout.close();
return 0;
}

#program to read and display from the file


#include<fstream>
#include<iostream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

char ch;

while(!fin.eof())
{
fin.get(ch);
cout << ch;
}

fin.close();
return 0;
}

Program to copy contents of file to another file.


#include<fstream>
using namespace std;

int main()
{
ifstream fin;
fin.open("out.txt");

ofstream fout;
fout.open("sample.txt");

char ch;

while(!fin.eof())
{
fin.get(ch);
fout << ch;
}

fin.close();
fout.close();
return 0;
}

You might also like