Você está na página 1de 48

C++ Material

Dept. of CSE, VVIT

C++
(Object Oriented Programming)
Introduction:
A language is basically for providing better communication between two or more
objects. There are certain language categories that provide communication between a
computer and its user. Such languages are said to be computer languages. They are
meant for better problem solving. In order to provide better instructions for problem
solving in any language, the language must posses various features. In fact, many
things can judge a languages efficiency. Some of the following:
A well defined syntax and semantic structure
Reliability
Fast translation
Efficient object code
Orthogonal
Machine independence
Provability
Genericity
Consistency
Uniformity
Extensibility
The process of problem solving may be referred as Programming. In computers,
programming techniques are classified in to 4 types. The list follows:

Monolithic Programming.

Procedural Programming.

Structured Programming.

Object Oriented Programming.

Monolithic Programming:
The programs written in these languages provide only global data & sequential code
that manage the data. It doesnt support any loops & functions concept. Only
branching statements like goto can be used.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

1
2
3
go to 100
------- --------------- --------go to 2
------- ---------

Global data

Assembly languages and Basic are the examples for monolithic programming.
Procedural Programming:
The program written in these languages provide both global data, sequential code
along with control structures.

Though these languages provide better programming

techniques, they do not support modular programming i.e., functions.


Global data

Sub programs
Fortran & COBOL are the examples for procedural language.
Structured Programming:
A new programming technique called structured programming has came into picture
after the procedural languages. It supports both control structures and functions in
addition to top down approach. In this approach, there is more concentration on
functions rather than data.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT


Global data

Sub-modules
Each program in this approach consists of several modules and each module has its
own local data along with the global data. Pascal & C are the examples for structured
programming languages. It becomes tedious to implement complex applications using
structured programming languages and even they are costly to implement.
Object Oriented Programming:
In order to develop large software systems, we require a better programming
approach compare to structured programming. Moreover, such systems require more
concentration rather than data. To achieve this, a new programming approach has
been developed called Object oriented programming where data may be organized in
terms of classes and objects to improve better accessibility and security to the data.
Object 1

Data

Object2

PRKP/KMK

Functions

Object 3

Data

Data

Functions

Functions

C++ Material

Dept. of CSE, VVIT

C++, Smalltalk, Java are the some of the examples for oop languages.
In Object oriented approach everything is identified in terms of objects or entities.
OOP is a method of implementation in which programs are organized as a
cooperative collection of objects, each of which represents an instance of
some class.
In OOP concept you find different jargon like class, object, data abstraction,
encapsulation. Here,
A class is a blue print for several objects. Or a class is a logical construct that doesnt
have any physical occupation. Or a class is a ADT (abstract data type) the defines a
set of properties and behavior as a unit. Or a class is a template that unites data and
functions.
Here we can assume that properties are nothing but data members and behavior
means operations or functions.
An object is an instance of a class. Or an object is a physical construct that occupies
certain amount of memory.
For example:
Class : Person
Properties: Name, age, sex.
Functions: listen(), speak()
Class: Student
Properties: stno, name, group
Functions: get(), put() etc.,

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Features of object oriented programming:


Object oriented programming is a method of implementation in which programs are
organized as a cooperative collection of objects, each of which represents an instance
of a class.
Any object oriented programming language allows the user to perform better
programming in addition to structured programming features.
The following is the list of OOPs concept:
o

classes

objects

Data abstraction

Data encapsulation.

Polymorphism

Inheritance

Templates

Persistence

Message passing.

Extensibility.

Classes & Objects: In OOP concept, a class & an objects are the basic units. Here a
class is a collection of data and its corresponding member functions and it is an
abstract data type. An object is a physical construct that holds certain amount of
memory and it is assumed as a runtime entity.
Data Abstraction: The process of creation of a new data type from already existing
data types is referred as data abstraction. In other words, the process of exhibiting the
essential information without revealing the background details is referred as data
abstraction.
Data Encapsulation: The process of wrapping up of data and its corresponding
member functions as a single unit is said to be data encapsulation. It leads to data
hiding. which disables unauthorized access to the data.
Polymorphism: Polymorphism is one of the striking features of any object oriented
programming language. Poly means many and morphism means forms. The ability
of providing multiple definitions to the same function name or operator is referred as
polymorphism.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Inheritance: Inheritance is one of the most striking features of OOPs concept. The
process of extracting the features of one class into another is said to be inheritance.
The main objective of inheritance is to provide code reusability.
Templates: A template is a generic function that works on different types of data.
OOPs supports generic programming. It is one of the advanced concepts of c++.
Persistence: The process of providing life to objects even after completion of

program is called persistence. I.e., one can made objects permanent through I/O
streams.
Message Passing: The process of invoking any operation on an object is referred as
message passing.
Extensibility:

The process of providing convenient environment where software

components can have extensions to itself. It is possible by abstract classes using


inheritance.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Introduction to C++

Bjarne Stroustrup invented C++ at AT&T Bell labs as an extension to C in the year
1980. The initial name of C++ was C with Classes. As C++ is an extension to C, it
supports all the concepts of C. Hence the learner may not feel C++ as a completely
new language.
In fact, C++ is not meant for simple applications. Its usage may be extended to
complex applications as it uses classes and objects.
Either Borland C++ or Turbo C++ or ANSI C++ compiler may be used for developing
applications.
For any language, the smallest individual units are in a program are called as tokens.
The C++ tokens are:

Keywords.

Data Types.

Operators.

Identifiers.

Constants.

Strings.

Note :
C++ supports 48 keywords including all the 32 keywords of C.
In addition to C data types, some other data types are also available.
In addition to C operators, more number of operators list is also provided.
Some of the operators that are additional in C++ are:

PRKP/KMK

::

scope resolution operator

.*

Pointer to a member operator

->*

Pointer to a member operator

new

memory allocation operator

delete

memory de-allocation operator

endl

line feed operator

<<

insertion operator

>>

extraction operator

setw

set width operator.

Etc.,

C++ Material

Dept. of CSE, VVIT

Structure of C++ Program:


link Section
class Declaration
class class name
{
private Section
(declaration of data members)
protected section
(declaration of either data members or member

functions)

public section
(declaration of either data members or member

functions)

};
class member function definitions
void main()
{
-----------------}
Note:
1. Either single line or multi-line commenting may be used in C++.
2. Every class definition must be terminated by semi coolen.
3. For every class there must be an object in order to make a call to the
function.
4. There may be any no. of objects for a class.
5. One program may have any no. of classes.
Standard I/O operations:
In C++ the basic Input and output operations can be performed using predefined
stream I/O objects called cout & cin.

PRKP/KMK

cout

console output

cin

console input.

C++ Material

Dept. of CSE, VVIT

A sample C++ Program:


Void main()
{
int a, b, c;
cout<< Enter a, b;
cin>>a>>b;
c = a + b;
cout<<c = <<c;
}
cout To display any value or string on to the console or screen.
Cin

- To read values in to variables.

cout

<<

Keyboard

cin

Example for a class:


Class demo
{
private:
int a, b;
public:
void getdata()
{
cout<<Enter a,b;
cin>>a>>b;
}
PRKP/KMK

c++ is an oop language

>>

A,B

C++ Material

Dept. of CSE, VVIT


void putdata()
{
cout<<a<<b;
}
};
void main()
{
demo d; // creation of object.
d. getdata();
d. putdata();
}

Scope Resolution Operator:

It is a new operator in C++ that has a lot no. of

advantages. It is used to define the scope of a variable and is used to define member
functions of a class outside the class.
For ex1:
#include<iostream.h>
int a = 10;

//global variable

void main()
{
int a = 20;
for (int k = 0; k<4 ; k++)
{
cout<<k<<endl; // prints local variable
cout<<::k<<endl;// prints global variable
}
}
Note: Runtime declaration of variables may be performed in C++. In the above
example k was declared when it is required. Variables may be declared anywhere in
the program.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Ex2:
#include<iostream.h>
class test
{
int a,b;
public:
void get();
void put();
};
void test ::get()
{
a = 10;
b = 20;
}
void test :: put()
{
cout<<a<<b<<endl;
}
void main()
{
test t;
t . get ();
t . put ();
}

Reference Variables
A reference variable creates an alias name to a variable. I.e., more than one reference
name (variable name) may be there to the same data. It provides the behavior of a
pointer variable. However, it may not be as flexible as a pointer. Moreover a reference
variable must be initialized at the time of declaration itself. Another point to be noted
is, an alias name may be created to a constant value. I.e.,
For ex:
int A = 10;
Int &B = A; // valid;
PRKP/KMK

C++ Material

Dept. of CSE, VVIT


Int &k = 200; // invalid as it is a constant.

Note: In the above example

int &B = A; , B is called as Independent Reference.

Symbolic Representation is::::


Actual name
Memory

A,B
Note:

alias name (or) reference


Data or value
address

10
1005

1.No separate memory is allotted to a reference variable; instead, it refers to


an existed data.
2. References concept even applied on objects.
Restrictions on References:
We cannot create reference to a reference.
We cannot create array of references.
We cannot create a pointer to a reference.
Unlike null pointers, null references are prohibited. In other words like null
pointers, we cannot have null references.

Inline Functions:
An Inline function is similar to a macro in its behavior. It never gets through overheads
like loading, compilation and debugging as the normal functions have. It improves
program execution speed. In fact, a macro never gets compiled; instead, it replaces
the statement with the required statement.
In order to develop an inline function, one has to precede a keyword inline to the
function definition.
Syntax is:
Inline return type function name (arguments list)
{
body of function;
}
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Example:
# include <iostream.h>
void main()
{
int k;
cout<<Enter k;
cin>>k;
k = cube(k);
cout<<The value of k is<<k;
}
inline int cube(int z)
{
return (z*z*z);
}
Before implementing Inline Functions, remember the following:

An inline function should not be recursive.

An inline function should not contain complex control structures like switch and
goto.

An inline function should not use static keyword.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Static Data Members & Static Functions

A data member of a class can be declared as static data member. The behavior of
static data member resembles C static variables.

It is initialized to zero when the first of the class is created. No other


initialization is permitted.

Only one copy of static data member is created for entire class. Hence all the
objects of the class share the same data member..

Its scope is within the class in which it is defined.

Its life is through out the program

Definition might be inside or outside of the class. While defining outside, it must
precede class name and scope resolution operator.

Syntax:

return type class name :: static data member name;

For example: Let demo is a class and count is a data member.


Int demo :: count = 20;
A static data member is usually referred as class variable because it is associated with
the class itself rather than object of the class.
Static Function:

Similar to a data member, a function may be defined as static.

Every static function has the following properties:

A static function can have access to static data only.

A static function does not require any objects in order to call itself.

i.e., we use class name & scope resolution operator to call a static function.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Friend Functions

A friend function is a special kind of function used to access private data of a class. It
is a function implemented only in C++. A non-member function that has access to the
private data of a class is nothing but friend function.
In order to implement friend functions, use friend keyword while defining the
function. The declaration of the friend function must be in the class but the
corresponding definition must be outside the class. Though the declaration is there in
the class, the function is not supposed to be part of the class. More than one object of
the same class or more than one class can be accessed by a friend function.
Some times we may raise a situation where more than one class wants to share the
same function. In such situations friend functions are the best choice.
In order to implement friend functions, one has to remember the following:

A friend keyword is to be preceded before the function declaration.

Function definition shouldnt contain friend keyword.

Only the declaration of friend function must be within the class but the definition
should be outside class.

While calling the friend function, you need not to create object or use object.

Pass objects as arguments to the friend functions.

If Friend function trying to access objects of more than one class, then the
declaration must be in all the classes.

It can be defined in either public or private part of the class.

Syntax: Friend return type function name (arguments list);


Ex:

Friend void test(demo d);

Example:
Class student
{
int stno;
char stname[10];
PRKP/KMK

C++ Material

Dept. of CSE, VVIT


int m1,m2,m3,total;

public:
void get_info()
{
cout<<Enter student no;
cin>>stno;
cout<<enter student name;
cin>>stname;
cout<<Enter m1,m2,m3;
cin>>m1>>m2>>m3;
}
void find_total()
{
total = m1+m2+m3; //calculating total marks
}
void disp_info()
{
cout<<Stno = <<stno<<endl;
cout<<Name =<<stname<<endl;
cout<<Total = <<total<<endl;
}
friend student highest_marks (student, student, student);
//friend function declaration.
}; //end of class.
Student highest_marks(student s1, student s2, student s3)
{
if((s1.total>s2.total)&&(s1.total>s3.total))
return s1;
else
if ((s2.total>s1.total)&&(s2.total>s3.total))
return s2;
else
return s3;
} //end of friend function definition.
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

void main()
{
student s1,s2,s3, s;
s1.get_info(); s1.find_total();
s2.get_info(); s2.find_total();
s3.get_info(); s3.find_total();
s = highest_marks (s1, s2, s3); //calling friend function
s.disp_info();
}

PRKP/KMK

//displaying student info. With highest marks.

C++ Material

Dept. of CSE, VVIT

Constructors & Destructors

A constructor is a special type of member function that initializes an object of a class.


Or a constructor is a member function that gets invoked at the time of creation of an
object.
In fact, in every class, there may be one or more data member that are needed to be
initialized by invoking a member function. Usually the user writes a member function
that does the same job. To reduce burden over the programmer to certain extent one
can define a constructor to which no explicit call is required. A constructor function has
an implicit call to itself every time the user creates an object.
In order to define a constructor, remember the following:
1. It should have the same name as class name.
2. It should not return any value; even void should not be mentioned.
3. It should always be in the scope of public section of the class.
Ex:
Class Demo
{
int a;
public:
Demo()
{
a = 10;
}
void show()
{
cout<< Value of a is<<a<<endl;
}
};
void main()
{
Demo d; // it automatically invokes Demo() constructor;
d.show();
}
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Constructors are 3 different types:

Default constructor.

Parameterized Constructor.

Copy constructor.

A constructor that has no arguments is referred as a Default Constructor. In the


above example Demo() can be assumed as a default constructor.
A constructor that has one or more data as arguments to it self is called as a
parameterized constructor.
A constructor that uses new operator is referred as dynamic constructor.
A constructor accepts the reference of the object of the class, in which it is defined,
as argument is said to be a copy constructor.
Destructor:
Usually when objects go beyond the scope of the user, they may be destroyed. A
destructor is a member function that destroys the objects of a class. Or a destructor is
a member function that gets invoked when an object is destroyed.

Like a constructor, destructor also has the same name as its class name.

One class must have only one destructor.

Destructor definition must be prefixed by a character tilde (~).

It doesnt return any value. Even void should not be mentioned.

Unlike constructors, destructors do not have arguments.

Example:
Class demo
{
public:
demo()
{
cout<<this is a demo program<<endl;
cout<<Object was initialized<<endl;
cout<<through the constructor<<endl;
PRKP/KMK

C++ Material

Dept. of CSE, VVIT


}
~demo()
{
cout<<Object has been destroyed<<endl;
cout<<As the destructor was invoked;
}
};
void main()
{
demo d;
}

Output:

this is a demo program


Object was initialized
Through the constructor
Object has been destroyed
As the destructor was invoked.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Polymorphism

Polymorphism is one of the striking features of any Object Oriented language. Poly
means many & morphism means forms. The process of providing multiple forms is
referred as polymorphism.
Polymorphism is classified in to two types:
1. Compile time polymorphism.
2. Runtime Polymorphism.
The Other classification is:
1. Function Overloading.
2. Operator Overloading.
Function Overloading: The process of providing multiple definitions to the same
function signature is referred as function overloading. In other words, the process of
extending the capability of the same function signature by providing more definitions
may be called as function overloading.
In fact, as per any other nonoops based language, one function should have one
function definition i.e., unique function name & definition may be there for every
function.
This process may increase the clarity of the program and reduces complexity of the
language to some extent.
In function overloading, functions may be differentiated by the number of arguments,
type of arguments and the order of the arguments passed to the function. The function
signature doesnt include the return type.
For example:
Return type function name(arguments list);

Function signature

#include<iostream.h>
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

class sample
{
public:
void show(int a)
{
cout<<Integer is::::<<a<<endl;
}
void show(char a)
{
cout<<Character is::::<<a<<endl;
}
void show(float a)
{
cout<<Float value is::::<<a<<endl;
}
};
void main()
{
sample s;
s.show(89);
s.show( M );
s.show(123.4f);
}
o/p:-

Integer is::::89
Character is::::M
Float value is::::123.4

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Operator Overloading:
Usually operators are meant for performing operations on standard data types in
normal programming languages. But C++ allows the operators play another vital role
in overloading. The process of extending the capability of an operator by providing
additional definition is referred as operator overloading.
Consider an example, the operator + is able to perform arithmetic addition over the
numeric data. But its capability may be extended to strings & objects. Hence we say,
operators allow polymorphism i.e., performing many actions with a single operator.
However, we do not disturb the actual meaning of the operator.
Most of the C++ operators may be overloaded. In order to overload any operator, use
operator keyword. Initially we write an operator function to assign a new definition to
the operator. Such definition must precede operator keyword.
Syntax:
Return type operator Operator Symbol (arguments list);
{
// body of the function
}
Both unary & binary operators may be overloaded but not the ternary operator.
An operator function may be a friend function.
Ex1: void operator +(complex);
Complex operator +(complex, complex);
Void operator ==(string, string);
The following is the list of operators that cant be overloaded:

PRKP/KMK

Operator Category

Operator

1. Member access

(dot operator)

2. Scope resolution

::

3. Conditional

?:

4. Size of data type

size of

5. Pointer to member

C++ Material

Dept. of CSE, VVIT

#include<iostream.h>
class string
{
char str[20];
public:
string()
{
cout<<Enter any string;
cin>>str;
}
void show()
{
cout<<String is..<<str<<endl;
}
void operator +(string &s)
{
strcat(str,s.str);
}
};
void main()
{
string s1,s2;
s1.show();
s2.show();
s1+s2;
s1.show();
}
In the above example strings of s2 is concatenated to string of s1. To implement this,
we have used operator overloading. An operator + is overloaded i.e., an operator
function is written.
Here the statement s1+s2; is converted as s1. +(s2);
Moreover, an operator function can be a friend function. In the above example, if the
operator function was written as friend then the statement s1+s2; is converted as:
S1+S2; --
PRKP/KMK

+(S1,S2);

C++ Material

Dept. of CSE, VVIT

i.e., the function might be declared & implemented as follows:


friend void

Inheritance
Inheritance is the most striking feature of OOP language that allows hierarchical
classifications. Or Inheritance is a technique of organizing information in a hierarchical
form. Inheritance is a process of extracting the features of one class into another. The
main object of inheritance is reusability.
In some other way, inheritance allows new classes to be built from the older or
existing classes instead of rewriting again. In this approach, multiple classes are
involved. Moreover, apart from private & public access specifiers, it allows protected
specifier.
Types of Inheritances:

B
Single Inheritance

Multiple Inheritance

B
B

C
C

Hierarchical Inheritance

Multi-level Inheritance

D
Hybrid Inheritance

PRKP/KMK

Multi-path Inheritance

C++ Material

Dept. of CSE, VVIT

Once the inheritance concept is implemented, the member functions and data
members of base class may be used in derived as if they are defined in the derived
class itself.
Single Inheritance: The process of extracting the features of one class into another
class is referred as single inheritance. In this approach, two classes are involved in
which one class is base class and the other class is derived class.
Syntax:
Class base class name
{
------;
------;
};
Class base derived name : visibility specifier base class name
{
-------;
-------;
};
Ex:

Class demo
{
------;
------;
};
Class derived : public demo
{
-------;
-------;
};

Multiple Inheritance: In this approach, multiple base classes and a single derived
class is existed.
Syntax:
Class base1
{
------;
------;
};
Class base2
{
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

------;
------;
};
Class derived : visibility specifier base1, visibility specifier base2....
{
-------;
-------;
};
Multi-level Inheritance: In multi-level, more than one base & derived classes are
existed. A class that acts as both base & derived class is referred as intermediate base
class.
Class base
{
------;
------;
};
Class intermediate base : visibility specifier base
{
------;
------;
};
Class derived : visibility specifier intermediate base
{
-------;
-------;
};
Hierarchical Inheritance: In hierarchical, one single base class is being inherited by
multiple derived classes.
Class base
{
------;
------;
};
Class derived1: visibility specifier base
{
------;
------;
};
Class derived2 : visibility specifier base
{
-------;
-------;
};
Class derived3 : visibility specifier base
{
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

-------;
-------;
};
Hybrid Inheritance: A inheritance that includes more than one type of inheritance or
a inheritance that is combination of multiple inheritances is referred as hybrid
inheritance.
Access Specifiers in C++
C++ supports three different access specifiers called private, public and protected.
They specify how the data members of the classes that are involved in inheritance may
be accessed.

Private data members are always private. They are highly restrictive data
members.

Public data members have global accessibility. They can be directly accessed or
indirectly through the object of the class.

Protected data members acts sometimes as private & sometimes as public. This
can be implemented only in inheritance concept. In case of independent classes
that do not inherit any of the existing classes protected data members act as
private, i.e., for all non-derived classes protected data members are private. For
all derived classes, protected data members act as public.

Function Type

Private

Public

Protected

Class member

Yes

Yes

Yes

Derived class member

No

Yes

Yes

Friend

Yes

Yes

Yes

Friend class member

Yes

Yes

Yes

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Constructors in Inheritance:
In inheritance, constructors & destructors may be implemented based on the
requirement. Both base & derived classes can have constructors. In such cases, if we
create object for the derived class, the corresponding base class constructor gets
invoked first, then the derived class constructor. Even a base class constructor may be
there without having to create derived class constructor.
Ex:
Class sample
{
public:
sample()
{
cout<<Base class constructor<<endl;
}
};
class test : public sample
{
public:
test()
{
cout<<Derived class constructor;
}
};
void main()
{
test t; // object of derived class that invokes constructors.
}
o/p:-

Base class constructor


Derived class constructor

Some times we may require implementing parameterized constructors in inheritance.


In such cases we send arguments to the base class constructor through the derived
class constructor.
Ex:
Class sample
{
int a;
public:
sample(int k)
{
a = k;
cout<<Base :<<a<<endl;
PRKP/KMK

C++ Material

Dept. of CSE, VVIT


}

};
class test : public sample
{
int b;
public:
test(int m, int n) : sample(n)
{
b = m;
cout<<Derived :<<b;
}
};
void main()
{
test t(33,99); // object of derived class that invokes constructors.
}

Note: Here 33 and 99 are passed to derived class constructor as m & n. From there
value of n is sent to the base class constructor.
Virtual Base Classes: In multi-path inheritance, multiple copies of the base class will
exist in the corresponding derived class through intermediate base classes. In such
situations, ambiguity comes into picture. Here we are required to ignore any one of the
copies from the existed. In order to achieve this we have two ways to follow:
a. Make the base class as virtual base class.
b. Use scope resolution operator.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Example:
#include <iostream.h>
class DEMO
{
public:
int a;
};
class SUB_DEMO1:public DEMO
{
public:
int b;
};
class SUB_DEMO2:public DEMO
{
public:
int c;
};
class SUB_DEMO3:public SUB_DEMO1, public SUB_DEMO2
{
public:
int sum;
};
void main()
{
SUB_DEMO3 d;
d.SUB_DEMO1::a = 1;
d.SUB_DEMO2::a = 2;
d.b = 6;
d.c = 7;
d.sum=d.SUB_DEMO1::a + d.b + d.c;

// 1 + 6 + 7

cout <<"sum = "<<d.sum;


cout <<"sub_demo1 a "<< d.SUB_DEMO1::a;

// Displays 1

cout <<"sub_demo2 a "<< d.SUB_DEMO2::a; // Displays 2


}

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Using Virtual Base Classes:::::::::


Ex:#include <iostream.h>
class DEMO
{
public:
int a;
};
class SUB_DEMO1 : virtual public DEMO
{
public:
int b;
};
class SUB_DEMO2 : virtual public DEMO
{
public:
int c;
};
class SUB_DEMO3:public SUB_DEMO1, public SUB_DEMO2
{
public:
int sum;
};
void main()
{
SUB_DEMO3 d;
d.a=5;
d.a=2;
d.b=3;
d.c=30;
d.sum=d.a+d.b+d.c;

// 5 + 2 + 3

cout <<"sum = "<<d.sum;


cout <<"sub_demo1 a "<< d.SUB_DEMO1::a; // Displays 20
cout <<"sub_demo2 a "<< d.SUB_DEMO2::a; // Displays 20
}

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Virtual Functions
A virtual function is a member function that is declared within a base class and
redefined by a derived class. To create a virtual function, precede the functions
declaration in the base class with the keyword virtual.
To be more specific, virtual functions concept allows users to have more than
one definition to the same function signature i.e., it allows One interface multiple
methods.
In some other way, a class may have a function whose definition is available in the
corresponding derived class.

The main capability of virtual functions is runtime

polymorphism. When a base pointer points to a derived object that contains a virtual
function, C++ determines which version of that function to call based upon the type of
object pointed to by the pointer.
Usually the process of providing multiple definitions to the same function signature in
both base & derived classes may be referred as function overriding. Such function
overriding can be achieved by virtual functions. A class that has virtual function may
be referred as polymorphic class. In order to achieve flexibility of virtual functions, one
has to implement object pointers.
Example:

Class base
{
public:
virtual void demo()
{
cout<<Base class function;
}
};
class first : public base
{
public:
void demo()
{
cout<<Frist Derived class function;
}
};
class second : public base
{
public:
void demo()
{

PRKP/KMK

C++ Material

Dept. of CSE, VVIT


cout<<Second Derived class function;
};

void main()
{
base *p; //base class pointer
base v;
first f;
second s;
p = &v;
p->demo(); //base class function
p = &f;
p->demo();//first derived class function
p = &s;
p->demo(); //second class function
}
Note: In fact, if we try to access demo() through the object of derived class, it always
accesses the derived class function.
Some times the user may not have anything to implement the base class function. In
such cases, the function may be defined as a pure virtual function i.e., a pure virtual
function that has no definition within the base class. To define a pure virtual function,
use the following:
Syntax:

Virtual return type function name (arguments list) = 0;

Example:
Virtual void show() = 0;
Rules for Virtual Functions:
1. A virtual function may not be static.
2. It can be a friend function to another class.
3. Object pointers access them.
4. It should be in public section of the class.
5. Prototype in the base & derived must be identical.
6. There can be virtual destructors but not virtual constructors.
7. Use object pointers for the base class only.
8. It is used majorly in hierarchical inheritance.
C++ maintains a virtual table that holds the addresses of the function. When C++
statements call these member functions, the correct address is fetched from the table;

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

this process may consume some time. However, virtual functions provide lot of
flexibility to the users.
Abstract Class: A class that contains at least one pure virtual function is said to be an
abstract class. Moreover, we cant create an object for such classes.
Finally we conclude that virtual functions achieve runtime polymorphism. In this
approach, we find new words like early binding and late binding.
Early Binding refers to events that occur at compile time i.e., early binding occurs
when all information needed to call a function is known at compile time. In some other
way, object and the corresponding function call may bound at compilation. This is
referred to static binding or early binding.
On the other hand, late binding is opposite to early binding. It refers to the function
calls that are not resolved until runtime. This is also referred as runtime binding or
dynamic binding.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

I/O Streams
Every program must under go a process of input - computation - output so that it can
take input and send the processed data as output. Usually, c++ provides such a
mechanism through objects like cin and cout with the stream operators >> , <<.
Moreover, streams and their handling mechanism are done with console I/O and disk
I/O.
A stream is a collection of or sequence of character data. In some other way, a stream
is series of bytes, which act either as a source from which input data can be extracted
or as a destination to which the output can be sent.
The input and output are managed by and I/O system and it in turn is designed to
operate on a wide variety of devices including consoles, disks and printers etc.,
The following diagram resembles the whole system:
Streams are classified into two categories:
Input streams.
Output streams.
An input stream allows the user to perform only input operations (read operations)
where as output streams allow to perform output operations(write operations).
The I/O operations are also categorized as follows:
Console I/O.
File I/O or Disk I/O
Predefined C++ stream objects:
C++ provides these predefined stream objects:
Cin

Standard input

Cout

Standard output

cerr

Standard error

Clog

PRKP/KMK

usually keyboard,
corresponding to stdin
in C
usually screen,
corresponding to stdout
in C
usually screen,
corresponding to stderr
in C
A fully-buffered version
of cerr (no C equivalent)

C++ Material

Dept. of CSE, VVIT

You can redirect cin, cout, cerr, and clog from and to other devices and files.
IOStream Class

What It Does

Streambuf

Provides methods for memory buffers.

ios

Handles stream state variables and errors.

istream

Handles formatted and unformatted character


conversions. It defines input functions such as get( ),
getline( ) and read( ).
In addition it has an operator
overloaded function for the operator >> , to read data
from input device.

ostream

Handles formatted and unformatted character conversions


to a streambuf. It defines output functions such as put ()
and write(). In addition it has an operator-overloaded
function for the operator <<, to write data to an output
device.

iostream

Combines istream and ostream to handle bi-directional


operations on a single stream.
Provides constructors and assignment operators for the
cin
- Provides constructors and assignment operators for
cout, cerr and clog.

istream_withassign
ostream_withassign

Console Stream class hierarchy : -

(IOSTREAM.H)

ios

istream

streambuf

ostream

iostream
Istream_
withassig
n

PRKP/KMK

Iostream_
withassign

Ostream_
withassig
n

C++ Material

Dept. of CSE, VVIT

Unformatted Console I/O operations : The most commonly used objects throughout the c++ program are cin & cout. They
are predefined

in iostream.h. These objects are used by overloading operators >>,

<< respectively.
The other functions are :
Void get( char &); - to read a single character.
Int get();
- to read a single integer value.
Istream& getline(char *, int length) - to read a char. Array.
Ostream :: write(char * buffer, int length) used to write any char. Data.
Formatted Console I/O operations : Most programs need to output data in various styles. A common requirement is to
reserve an area to format the output. To do this, there must be a provision for
alignment of the data. C++ provides variety of features to perform i/o in different
formats. This can be achieved using :
a) ios stream class member functions and flags.
b) Predefined manipulators.
The ios stream class class provides several member functions to assist in designing the
output in number of ways. The general functions are :
1) width ( )

2) precision ( ) :

To specify the no. of spaces for a specified field.


Syntax :
int width(int);
Ex :
cout . width(5);
To specify the no. of digits to be displayed after the decimal part.
Syntax :
int precision(int);
Ex :
cout . precision(7);

3) Fill( )

it specifies a character to be used to fill the unused area of a field.


By default, a blank space is considered.
Syntax :
int fill(char);
Ex:
Cout . fill(*);

4) setf ( )

uses flags that control the form of output display.


Syntax :
long setf (flag , bitfield);
Ex :
cout . setf (ios::oct, basefield);

5) unsetf( )

clears the specified flag or all the flags.


Syntax :
long unsetf(flag);

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

The following is the list of flags that have bit field option : -

FLAGS

BITFIELDS

EFFECTS PRODUCED

ios::left
ios::right
ios::internal

ios::adjustfield
ios::adjustfield
ios::adjustfield

left justified output.


right justified output.
padding occurs between
the sign or base indicator
and the number, when the
number output fails to fill
the full width of the field.

ios::dec
ios::oct
ios::hex

ios::basefield
ios::basefield
ios::basefield

decimal conversion.
octal conversion.
hexadecimal conversion.

ios::scientific

ios::floatfield

ios::fixed

ios::floatfield

use exponential floating


notation.
use ordinary floating
notation

The following is the list of flags that do not use bitfields :


Flag

Effect Produced

Ios:: showbase
Ios:: showpos
Ios:: showpoint
Ios:: uppercase
Ios::stdio

use base indicator on output


add + to positive integers.
includes decimal point and trailing zeroes in output.
uppercase hex output.
flush stdout and stderr after insertion.

Manipulators : A mainpulator is a function that can be used in association of << and >> operators
to format the output or to alter the behaviour of the cin and cout objects. Manipualtors
are classified into two categories :
1) parameterized manipulators.
2) Non parameterized manipulators.

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

The following is the list of parameterized manipulators :

Manipulator

action performed

1) setw (int width)

equivalent to

sets field width and hence


it is known as setwidth or
fieldwidth operator.

width( ).

2) setprecision(int prec) sets floating point precision

precision().

3) setbase(int base)

sets the conversion base


0 : base 10 is the output.
8 : use octal for the i/o.
10 : use decimal for i/o.
16 : use hexadecimal for i/o.

4) setfill ( char)

fills the spaces with the given char.

Fill().

5) setiosflags(long flag)

sets various flags for formatting.

Setf ( ).

6) resetiosflags(long flag) resets the specified flag.

Unsetf( ).

The non parameterized maniputlators are endl, ends, ws, dec, oct, hex etc.,

FILE I/O
A file is a collection of related information stored permanently in disk or a file is a
collection of character data.

The c++ i/o system

uses file objects as interface

between the programs and files. The streams that supply the data to programs are
referred as input streams and the one that receive data from the program is known as
output stream.
In other words, we say an input stream reads data from the file & an output stream
writes data to the file.
In fact, no external device will be in direct communication and hence a stream is
associated with each device.
The stream object itself performs the necessary
operation.
The general operations that can be performed with a file are :
i.
ii.
iii.
iv.
PRKP/KMK

Naming a file.
Opening a file.
Processing the file( i.e., performing read/write operation).
Closing the file.

C++ Material

Dept. of CSE, VVIT

The console I/O & File I/O hierarchy is : -

streamb

ios

uf

ostream

istream

Streamb
uf
ifstream

fstream

ofstream

filebuf

fstreambase

Mode and inherits the following functions from istream class.


Get( )
Getline( )
Read( )
Seekg( )
Tellg( )
Ofstream : It provides output operations. It contains function open( ) with default Write mode.
The other operations that are inherited from ostream are :
Put( ) , seekp( ), tellp( ) and write( ).
Fstream : It provides support for simulteneous input & output operations. It contains Open( )
with default modes to read and write inherited from istream and Ostream class.
However, mode of operation can be specified. C++ support Various file modes. These
modes are available in terms of flag of Ios class. The list is :

PRKP/KMK

FILE MODE

MEANING

Ios:: app

Append to end of file.

C++ Material

Dept. of CSE, VVIT


Ios:: ate
Ios::binary
Ios:: in
Ios:: out
Ios:: nocreate

Go to end
To open a
To open a
To open a
Open fails

of file on opening.
binary file .
file in read mode.
file in write mode.
if the file doesnt exists.

By creating objects to these objects one can achieve i/o operations to the disk files.
The objects create file pointers to perform operations. The file pointers are get pointer
(input pointer) & put pointer (output pointer). These pointers facilitate the movement
across the file while reading and writing.
ex1 : - (for writing data on to a file )
#include <iostream.h>
void main()
{
char name[20];
int marks;
ofstream myobject (st.dat); //creation of output object
cout<<enter name;
cin>>name;
cout<<enter marks;
cin>>marks;
myobject << name<<endl<<marks<<endl; // this allows to store name & marks in
the file
st.dat through the object myobject.
}
ex2 : - ( reading the contents of a file)
#include <iostream.h>
void main()
{
char name[20];
int marks;
ifstream myobject (st.dat); //creation of input object to read contents.
myobject >> name;
myobject >> marks;
cout << name<<endl<<marks<<endl; // this allows to read name & marks from the
file
st.dat through the object myobject.
}
Actually, sequential access of data is done in files. These files allow random access
i.e., the file pointers can be kept at required location in the disk file. To place the
pointers at the required location, there is a list of functions.
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Seekg( ) - ifstream

- moves get file pointer to a specific location.

Seekp ( ) - ofstream - moves put file pointer to a specific location.


Tellg( ) - ifstream - returns the current position of the get pointer.
Tellp ( ) - ofstream - returns the current position of the put pointer.
Syntax : Istream & seekp(long offset, mode flag);
Ostream & seekp(long offset, mode flag);
The flag mode may be any one of the following :
Ios:: beg
Ios::cur
Ios:: end

--- seek from beginning of the file.


--- seek from the current location.
--- seek from the end of file.

Some of Seek calls & their actions : Fout.seekg(0 , ios::beg)


Fout.seekg(0,ios::cur)
Fout.seekg(0,ios::end)
Fout.seekg(n, ios::beg)
Fout.seekg(n,ios::cur)
Fout.seekg(-n, ios::cur)
Fout.seekg(-n,ios::end)
Fin.seekp(n,ios::beg)
Fin.seekp(-n,ios::cur)

goto the beginning of the file.


stay at the current location
goto end of file.
move to (n+1) byte location in the file.
move forward by n bytes from the current position.
move backward by n bytes from current position.
move backward by n bytes from end of the file.
moves write pointer to (n+1) byte location.
moves write pointer backward by n bytes.

ex3 : - ( using fstream class )


#include <iostream.h>
struct student
{
char name[20], group[6];
int marks;
};
void main()
{
struct student s;
fstream myobject (st.dat);
//creation of fstream object to perform both read & write operations.
cout<<enter name;
for(int =0;i<5;i++)
{
cin>>name;
cout<<enter marks;
PRKP/KMK

C++ Material

Dept. of CSE, VVIT

cin>>marks;
myobject.write((char *) &s,sizeof(s)); // this allows to store name & marks in the file
st.dat through the object myobject.
}
myobject.seekg(0,ios::beg);
cout<<Name of student<<Group<<Marks<<endl;
cout<<-------------------<<--------<<--------<<endl;
for(int I=0;I<5;I++)
{
myobject . read((char *) &s,sizeof(s));
cout<<s.name<<\t<<s.group<<\t<<s.marks<<endl;
}
}

PRKP/KMK

C++ Material

Dept. of CSE, VVIT

Templates
A template is a generic function that creates a generalized function that works
for all primitive or standard data types. In some other way a template defines a
general set of operations that will be applied to various types of data. The type of data
that the function operates upon is passed as a parameter. The process of creation of
such generic function is referred as generic programming.
Usually a program may consist of several functions that have a common
functionality but the operating data might be different. In such situations often we
define overloading concept. However, an extended version of overloading may be
observed in templates. With templates one can avoid rewriting of code again & again.
A generic function to be created uses a keyword called template. In fact, the
literal meaning of a template is nothing but a framework. The general form of a
template function definition is:
template <class Ttype>
return type function name( arguments list)
{
// body of function
}
Here Ttype is a placeholder name for a data type used in the function. It is only used
for replacing the actual data with it self. The keyword class specifies the generic data
type in the template declaration.
Example:

template <class T>


T addition(T a, T b)
{
T c;
c = a + b;
return c;
}

* More no. of generic data types may be defined. The following is the syntax for it:
Syntax:

PRKP/KMK

template <class Ttype1, class Ttype2>


return type function name ( arg. List)
{
// body of function
}

C++ Material

Dept. of CSE, VVIT

Points to be noted:
Template function can be overloaded.
Template function can have any no. of generic data types.
Even normal primitive data types may be associated with
generic data types.
Template keyword is to be used before every generic function.
Template classes:
A template class is a generalized class that uses any generic data type i.e., not only
generic functions even we can have generic classes, which are known to be template
classes. Generic classes are useful when a class uses logic that can be generalized.
The general form of a generic function follows:
Template <class Ttype>
Class class name
{
..
..
};
Here Ttype is a place holder name which will be specified when a class is instantiated.
Once you have created a generic class, you create a specific instance (or object) of
that class using the following format:
Class name <type> object name;

PRKP/KMK

C++ Material

Dept. of CSE, VVIT


Exception Handling

Sometimes when a program is executing, something occurs that is not quite normal.
For example, a user might enter an invalid filename; a file might contain corrupted
data; a network link could fail; the user may do illegal memory access. Circumstances
of this type are called exception conditions in any object-oriented languages & are
represented using objects.
Literally, a program may cause several errors during the process of execution. An error
can be a syntactical error or logical error. In other words, we say an error could be a
compile time error or runtime error. Such errors are supposed to be handled by the
user explicitly. A process of handling such errors is required.
Here a compile time error is an error occurred during compilation of program and a
runtime error occurs during execution. In C++, such runtime errors are known to be
Exceptions and the process of dealing such runtime errors or exceptions is said to be
exception handling. Clearly an exception is a runtime error.

PRKP/KMK

C++ Material
Dynamic Arrays

PRKP/KMK

Dept. of CSE, VVIT

Você também pode gostar