Sei sulla pagina 1di 32

1

CONTENTS
- Introduction to C++
- Overview of C++
- Features of C++
- Object Oriented Programming Concepts
- Features of C and Drawbacks in C
- Differences between C and C++
- Tokens in C++
o Character Set
o Keywords
o Variables and / or Identifiers
o Constants
o Data types
o Operators etc
- Control statements
o Selection statements
o Jumping statements
o Looping statements
- Classes and Objects
- Functions with arguments
- Advanced functions and Special functions
o Inline functions
o Friend functions
o Const functions
o Static functions
o Function overloading
o Operator overloading
o Default argument functions
o Call by value
o Call by reference
o Call by address
o Recursion etc
- Constructors and Destructors
- Inheritance
- Polymorphism
- Templates
- Exception Handling
- I/O Streams
- Files
- Namespace
- RTTI

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
2

Introduction to C++

It is an Object Oriented Programming language. “Bjarne Stroustrup” developed it. It is


an extension of ‘C’ language. Bjarne Stroustrup initially named it as “C with classes”.
Later in 1983, the name was changed into C++. The idea is that it is a super set of C.

Applications of C++
C++ is versatile language. Which supports the development of complex application. Such
as editors, computers, data base, communication system etc.

Benefits of OOPs
OOP promises greater programmer productivity, better quality of software and lesser
maintenance cost.

The principles of OOPs or advantages

? Through inheritance, we can eliminate redundant code.


? New programs can be built from standard modules. This leads to productivity and
saving of development time.
? Secure programs can be developed.
? Multiple instances of an object can co-exist.
? It is possible to map, objects in the problem domain to those in the program.
? It is easy to partition the work of project as objects.
? The data centered design approach enables to capture more details.
? Scalability. This means object oriented systems can be upgraded from small to
large system.
? Software complexity can be easily managed.

OOP concepts:

It is necessary to understand some of the concept used extensively in object


programming. These includes,
- Class
- Object
- Data Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Class :
Class is a specification of structures, instance variables, behavior (methods), and
inheritance for objects. Class is a template or user defined data type. Which can
combine the data as well as methods of an object.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
3

Def : A class is a set of objects that share of common behavior. A single object is
simply an instance of a class.
A class is represented by a box, which has three sections. The different sections are
as follows.
i. Class name
ii. List of properties or attributes
iii. List of methods or behavior
Eg. Animal, Plant, Vehicle, Furniture, Student etc.

Object :
It is an instance of a class. It is the basic run time entity in an object-oriented system.
It may represent a person, place, a thing and so on.
A problem is analyzed in terms of objects and the nature of communication
between them. Program objects should be chosen such that they much closely with
the real world objects.
Eg. Lion, Rose, Chair, Motorcycle, Ravi etc.

Abstraction :
It is a process of identifying data members and methods of a class as relevant to the
application in hand identifying essential data members is known as “Data
abstraction”. While identifying methods is known as “procedural abstraction”.

Encapsulation:
Encapsulation is binding of behavior and state to a particular object. It embodies
information hiding.
It hides the non-essential details of an object and shows only essential details.
Encapsulation promotes reuse of objects that performs certain well-defined tasks.

Polymorphism
‘Poly’ means ‘many’and ‘Morphism’ means ‘forms’.
Polymorphism means “single name,multiple forms”. A message can perform or
behavior differently for different objects.
Polymorphism helps to reducing the no. of functions to be remembered.
Ex.
1. A person assumes different roles in different scenarios in his life.
2. Conducting an exam() in class they got different marks.
3. The add() can perform addition operation etc.

Inheritance
It is a process of deriving new classes from existing ones. The new class inherits its
properties and behavior from its “Parent Class”. Such class is known as “Sub Class”
or “derived class” or “Child class”. Where as the class from which a new class is
derived is known as “super class” or “base class” or “Parent class”. The greatest
advantage of inheritance is reusability of code.

Eg. A child takes on the characteristics of the parents.


---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
4

C language Features:
C language is a “Structured Programming language.”. Structured programming means
“large program is divided into small programs”. This is also known as “Procedure
Oriented programming language.” or “Top down approach” or “Modular
programming” or “Step wise programming” or “Compartmental programming”.

Characteristics:
? Emphasis is on doing things.
? Large programs are divided into smaller programs .known as functions.
? Most of the functions shared global data.
? Data move openly around the system from function to function.
? Functions transform data from one form to another form.
? Employees’top-down approach in program design.
? Easy to solve a problem.
? Easy to understanding a problem.
? Easy to debugging of program.
? Reusability of the same code.

Draw backs:
? When no. of functions are increased. It becomes complex.
? Global data can be accessed by all the funs.
? Data programming dependency.
? It doesn’t model real world problems very well.
? It doesn’t have data security.

-------------------------------------------------------------------------------------------------------
Tokens
Def: The smallest individual unit in a program is called a ‘Token’.
There are different tokens used in a program.
- Character set
- Keywords
- Variables and / or Identifiers
- Constants
- Data types
- Operators etc.

Character set:
The group of symbols used in a programming language is called “character set”. It
allows the following characters.

Alphabets : a… z
A… Z

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
5

Digits : 0… 9

Special Characters : + - * / % > < ? ., : ;‘ “ [] { }\|=_( ) &


^
$ @#!~

White space :

Variables and / or Identifiers:


Variable means ‘the value of a quantity is changing during program execution’.
It is a user defined name given to the memory location, where the quantity is stored in
a memory is called a “Variable”.

Ex.
Data = 25;
Here, ‘data’is a name of the memory location given by the user. 25 is a quantity.

Rules for designing a variable name:


- It does not match with Keyword.
- First character must be an alphabet or special symbol (_) only.
- Remaining characters may be alphabets or digits or special symbol (_) only.
- Spaces or other special symbols are not allowed.

‘Identifier’ is the user defined name given to the function, class name, structure name
etc.

Constants:
A Constant means ‘fixed quantity’. It does not change their value during program
execution.
Constants are classified into two categories.
1. Numerical constants: These are formed with digits only.
i. Integers: These numerical constants do not allow any decimal point.
Ex. 100, -12354, 522601, -190, 9876543210 etc.

ii.Real / Float: These numerical constants can allow decimal point.


Ex. 3.143, -0.01746, 123.456, -2233.9988432 etc.

2. Character constants: These are formed with any character in the set.
i. Single character constant: Any single character placed in a single
quotes.
Ex. ‘A’, ‘k’, ‘@’, ‘8’, ‘+’etc.

ii.String constant: A group of characters in a pair of double quotes.


Ex. “visix”, “hello”, “koti”, “@siripurapu” etc.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
6

Data Types:
Def: A data type is a term which refers to the kinds of data that variables may hold in
the programming language.

Data types are classified into 3 categories.


1. Built–in Data types or Standard data types: These data types are defined by in
the compiler. Ex. int, long, float, double and char.
2. Derived Data types: These are formed with built-in data types.
Ex. Arrays, Pointers and Functions.
3. User defined data types: These are defined by the programmer.
Ex. Structures, Unions, Enumerations and Classes.

Operators:
Operator means ‘a special symbol’. That can perform a specified operation without
changing their meaning.
There are different types of operators in C++.
- Arithmetic operators [ + , - , *, / and % ]
- Relational operators [ <, >, <=, >=, = = and ! =]
- Logical operators [ &&, || and ! ]
- Assignment operator [ = ]
- Ternary operators [ ? and : ]
- Increment and Decrement operators [ ++ and - -]
- Bitwise operators [ &, | , ^, ~, >>, <<, >>>]
- Special operators [ #, , , . , -> , sizeof ]
- Reference operator [ & ]
- Scope resolution operator [ :: ]

All these operators are classified into different categories.


- Unary operators : These are formed with single operand with an operator.
Ex. Increment and Decrement operators.
- Binary operators: These are formed with two operands with an operator.
Ex. Arithmetic, Relational, Logical, etc.
- Ternary operators: These are formed with three operands with an operator.
Ex. Ternary operators

Control Statements
Def: To control the sequential flow of a program using certain statements are called
"Control Statements".

There are 3 categories of control statements.


1. Branching / Selection statements:
A block of code can execute based on given criteria (condition).
Eg:
i. Ternary operator statement (Conditional Operator Statement)
ii. if statements
iii. switch statement (multiple block statement)
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
7

2. Un-conditional / Jumping statements:


Without checking any condition can move the control from one location to
another location in a program.
Eg.
i. goto statement
ii. break "
iii. continue "
iv. return "

3. Looping / Iterative statements :


These control statements can repeat a block of code in specified no. of times or un
till the condition returns false.
Eg.
i. while loop
ii. do-while loop
iii. for loop

Advantages :
- To avoid the re-writing of the same code
- To reduce the length of a program
- Executing time is low
- Save memory space.
- Takes less time for executing a program.
- Debugging is easy.

General form of C++ program:

[ comments ]
including statements
[ defining statements ]

class definition
[Functions]

void main()
{
Declaration statements
I/O statements
Processing statements
[getch() ]
}

here, [ ] ? optional statements

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
8

Output instruction:
To display any data on the monitor (std. o/p device) using an instruction is said to be
“output instruction”.
Syn:
cout<< “Message” <<var ;
Ex.
cout<<”C++ is better than C”;

The above statement introduces two features. cout is an object, which represents standard
output. i.e. monitor. “<<” is known as “Insertion Operator”. This is used to display any
kind of data on the screen. This is an overloaded operation in C++ to handle output.

Input instruction:
To read any data from the keyboard (std. i/p device) using an instruction is said to be
“input instruction”.
Syn:
cin<< var1<<var2<<var3… ;
Ex.
cin<<num;
The above line of code introduces two things. Such as cin and >>. cin is an object, which
represents standard input. i.e. key board. Where as “>>” is known as “extraction
operator”. It is used to read any kind of data from keyboard. This is an over loaded
operator in C++ to handle input.

The iostream.h file:


The declaration such as cout, cin, <<, >> are available in this file. Hence in every C++
program it must be included.
Eg.
#include <iostream.h>

Class:
Class is a user defined data type like structure. Class is a collection of data members
(instance variables) and member functions (methods).
The general form of the class is,

class ClassName
{
specifier:
Data Members
specifier:
Member Functions
};

Construction of class object :


syn :
ClassName objname ;
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
9

Here, objname represents variable name of the data type className. Using this object
we can call member functions defined in the class with dot operator. Size of the object
means the sum of the sizes of the data members defined in the class.

State, Behavior and Identity an Object:

An object has the following characteristics –

o It has a STATE

o It may display a BEHAVIOR, and

o It has a unique IDENTITY

The state of an object is indicated by a set of attributes and the values of these attributes. The
behavior refers to the change of these attributes over a period of time.

“Behavior is how an object acts and reacts, in terms of its state changes and message passing”.
Each object has a unique Identity.

Message:

A message is transmitted by one object to another. A message is a request for an action to be


taken, and is accompanied by additional information needed to carry out the request.

Operating System:

An Operating System is a set of programs that manages the resources of a computer and its
interactions with users.

Compiler:

A compiler is a special program that processes the statements written in a particular programming
language and converts them into machine language.

Access Specifiers:
Access specifiers are the keywords that alter the meaning and accessibility of members of
a class. They are,
private public protected

private:
It can be applied to variables and methods. Private data members of a class are accessible
from within the class only. They can not be accessed from outside the class and its
subclass.
public:
It can be applied to variables (data members), methods and classes. Public member of
class can be accessed globally any other code. They can be accessed from outside the
class and sub class. A public class can be accessed from any directory.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
10

protected:
It can be applied to data members and methods. Protected member of a class can be
accessed from within the class, sub class in the same directory. It can not be accessed
from a non-subclass in different directory.

Note: When no access specifier is mentioned for a data member, method or class. It
assumes private.

Define Member Functions: The data members of a class must be declared within
the body of the class, whereas the member functions of the class can be defined in any
one of the following ways:

1. In side the class specification


2. Out side the class specification

The syntax of a member function definition changes depending on whether it is defined


inside or outside the class specification. However, irrespective of the location of their
definition (inside or outside a class), the member function must perform the same
operation. Therefore, the code inside the function body would be identical in both the
cases. The compiler treats these two types of functions definitions in a different manner.

1. MEMBER FUNCTIONS INSIDE THE CLASS :This member function declaration is


similar to a normal function definition except that it is enclosed within the body of a
class. All the member functions defined within the body of a class are treated as inline by
a default except those members having looping statements such as for, while etc. and also
depend on the compilers.
syn.:
class CLASSNAME
{
specifier:
Data Members
specifier:
//Member functions
returntype FunName(args list)
{
body of the function
}
… . … . …
};

2. MEMBER FUNCTIONS OUTSIDE THE CLASS:


Another method of defining a member function is to declare function prototype within
the body of a class and then define it outside the body of a class. Since the functions
defined outside the class specification have the same syntax as normal function, there
should be a mechanism of binding the functions to the class to which they belong. This is
done by using the scope resolution operator (::). It acts as an identity-label to inform the
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
11

compiler. The class to which the function belongs. The general format of a member
function definition is shown in the following. This form of syntax can be used with
members defined either inside or outside the body of a class.

Syn :
class CLASSNAME
{
specifier:
Data Members
specifier:
//Member functions
returntype FunName(args list);
… . … . …
};
returntype CLASSNAME :: FunName(Args list)
{
body of the fun.
}

The label classname :: informs the compiler that the member function is the member of
the class classname. The Scope of the function is restricted to only the objects and other
members of the class.

Private member functions:


In previous examples, we are declaring the members functions in public section only.
There are some situations we may declare certain functions to be hidden from the outside
class.
A private member function called by another member functions in the some class only.
Those member functions must be declared in public section in the class. Even an object
cannot invoke a private function using dot operator.

syn :
class CLASSNAME
{
specifier:
Data Members
specifier:
//Member functions
returntype FunName(args list);
… . … . …
};
returntype className :: fun1(args. list)
{
body of the function
}

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
12

returntupe className :: fun2(args. list)


{
body of the function
}

Static data member:


A data member of a class can be qualified as static the properties of a static data member
are very much similar to a static variable in C.
Characteristics of static data members :
1. It is initialized to zero when the first object of its class is created.
2. Only one copy of that member is created for any no. of objects we create.
3. It is visible only within the class, but its lifetime encompasses to entire program.
Syn:
Datatype className :: varName ;

Static member functions:


In C ++, like static data members we can have static member functions. The following
are the characteristics of static member functions.
1. A static function can have only access to other static member functions and
variables declared in the same class.
2. A static member function can be called using the class directly without creating
an object.
Syn : Classname :: funname();

Inline function:
Inline functions are the enhancements over normal function and tries to speed up the
program execution time unless the function is short. Which consists of a set of machine
language instructions. When you start a program the operating system loads these
instructions into the computer’s memory. So, each instruction has particular member
Address. The computer then goes through these instructions step by step whenever it
encounters any fun. Call it jumps to a different member address and jumps back when the
fun terminates.

This is a function. Whose compiled code is “inline” with the other code in the program.
With inline code the program does not have to jump to another location. To execute the
code then jump back.

Syn:
inline returntype funname(args list)
{
body of the fun;
};

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
13

Friend Functions:
Generally a non member function cannot access the private data of a class. It is possible
that the outside funs. Which is a “Friend” can access the data of these classes.

The function definition doesn’t use either the keyword friend or the scope resolution
operator (::). The functions that are declared with the keyword friend are known as
“friend function”. A function can be declared as a “friend” in any no. of classes.

Notes:
1. It is not in the scope of the class to which it has been declared as friend.
2. It can be invoked like a normal function without any help of an object.
3. An object of each class is passed as an argument to the function and it access the
private data member of class through arguments.
4. A friend function operates upon the object or objects passed to it as arguments.
5. It can be declared either in the public or the private section of a class without
affecting the meaning.

Friend classes:
A class can also be made a friend of another class. All the members of the outer class can
now be accessed from the class inner.

Syn.
class OUTER
{
… . … . … ..
friend class INNER;
… . … . … ..
};

Ex.
class Koti
{
… …
public:
//declare a friend class
friend class Eshwar ;

//member functions
void visix()
{
cout<<”VISIX Technologies”<<endl;
}
};

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
14

class Eshwar
{
… … … …
public:
// member function
void hello()
{
cout<<”this is hello() method”;
//creating an object to the Koti
Koti k;
//calling visix() method
k.visix();
}
};

void main()
{
clrscr();
Eshwar ee;
ee.hello();
getch();
}

Call by Value:
When values of built in types are passed as arguments to a function. It is known as Call
by value. The changes made to formal parameters in the called function are not reflected
in the actual arguments class.

Syn:
//function calling statement
[var ] = funname(primitive args);

Call by Address:
In this approach, an object or primitive variable is passed as an argument, which is
assigned to an object or primitive variable reference are directly reflected to actual
argument.

Syn:
// function calling statement
[var =] funname(&args);
here, args may be primitives or objects.

Call by Reference:
In this approach, an object or primitive variable is passed as an argument, which is
assigned to an object or primitive variable not reflected in the actual arguments class.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
15

Syn:
//function calling statement
[var=] funname (args);
here, args may be primitives or objects.

Recursion:
A function calling itself is called “Recursion”.
Syn:
returntype func1(args)
{
… … … … … … … ..
… … … … … … … .
//calling same function
func1(args);
}

Constant member function:


We can define a member function as const is called “Constant member function”. A
member function is declared as const that is said to be constant member function. The
variables, which are used in that function, do not change their values.

Syn:
//member function
returntype funname(args list) const
{
// body of a function
}

Constructors:
A constructor is a special member function. Whose main operation is to allocate the
required resources? Such as memory and initialize the objects of its class. A constructor
is distinct from other member functions of the class and same name of its class.

It is executed automatically when a class object is created the constructors are used for
initializing the class data members. The constructor has no return values.

The constructor of a class is the first member function to be executed automatically when
an object of the class is created.

The constructor can be defined either within or outside the body of a class. It can access
any member like all other member function both cannot be invoked explicitly and must
have public status to serve its purpose.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
16

Important points :

1. It is a special fun. It has same name as class name.


2. It must be in public section only.
3. it is used for initialization of data member
4. It will be invoked automatically at the time of object creation.
5. It cannot return any value.

Type of constructors :
There are basically 3 types. Those are,
1. Default constructor
2. Parameterized constructor
3. Copy constructor

1. Default constructor: The constructor, which can’t take any arguments, is called
“Default constructor”.
2. Parameterized constructor: The constructor, which can takes any arguments, is called
“Parameterized constructor”.
3. Copy constructor: The constructor, which can initialize the data members with another
constructor that is said to be “Copy constructor”.

The Default, Parameterized and copy constructors are declared in a class is called
“multiple constructors”. That means more than one constructor declared in a class, is
called “Multiple Constructors”.

Syn:
class Sample
{
specifier:
//data members
specifier:
//member functions
Sample()
{
// default constructor
}

Sample(primitive args)
{
// parameterized constructor
}

Sample(Sample &obj)
{
// copy constructor
}

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
17

returntype funname(argslist)
{
//body of the function
}
};

void main()
{
clrscr();
//creating objects
Sample s1; //invokes default constructor implicitly
Sample s2(primitive args); //invokes parameterized constructor implicitly
Sample s3(s1); //invokes copy constructor implicitly
//calling member functions with objects
getch();
}

Destructors:
A destructor as the name implies is used to destroy the objects that have been created by
a constructor. Like a constructor the destructor is a member function. Whose name is
same name as the class name? But, is preceded by a tilde (~).

A destructor never takes any arguments nor does it return any value. It will be invoked
implicitly by the compiler upon exit from the program to clean up the storage that is no
larger accessible.

Destructor can be utilized to find the no. of objects created in the program.

Syn :
~ CLASSNAME( )
{
Body of the destructor;
}

INHERITANCE:
In OOP one of the main features is reusability. To implement this feature in C++ using
the concept inheritance. Inheritance is the process of creating new class called “Derived
class” from existing or Base classes. The derived class inherits all the capabilities of the
Base class. But, can add embellishments (added extras) and refinements of its own.

The mechanism of deriving a new class from old one is called “Inheritance”. The old
class is referred to as the Base class and the new one is called the Derived class.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
18

Syn :
Class derclass :: visibilitymode Baseclass
{
body of the derived class;
};

Type of Inheritance:
There are 6 types of inheritance. Those are,
1. Single inheritance
2. Multiple “
3. Multi level “
4. Hierarchical “
5. Hybrid “
6. Multiple path “

Single Inheritance : A class, which is derived from only one base class is called “Single
Inheritance”.

Multiple Inheritance: A class, which is derived from more than one base class is called,
“Multiple Inheritance”.

Multi Level Inheritance: A class, which is derived from a derived class, is called
“Multilevel Inheritance”. The class A serves a base class for the derived class B. which in
turns serves as a base class for the derived class C. The class B is known as “Intermediate
class”. This chain of inheritance is called “Multi level Inheritance”.

Hierarchical Inheritance : The classes, which are derived from only one base class that
process is called “Hierarchical Inheritance”.

Hibrid Inheritance : A class, which is derived from hierarchical and multiple


inheritance is called “Hybrid Inheritance”.

Mulitple Path Inheritance : A class, which is derived from hierarchical, multiple and
single inheritance is called “Multiple Path Inheritance”.

Polymorphism
Polymorphism is one of the crucial features of CPP. It simply means “One name,
multiple forms”.
The concept of Polymorphism is implemented using the overloaded functions and
operators. The overloaded member functions are selected for invoking arguments both
type and number. This information is known to the compiler at the compile time and
therefore, compiler is able to select the appropriate functions for a particular call at the
compile time itself. This is called “Early Binding” or “Static Binding” or “Static
Linking”. Also known as “Compile time polymorphism”. Early binding simply means that
an object is bound to its functions call at compile time. The appropriate member function
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
19

could be selected while the program is running. This is known as “Run time
polymorphism”. This function is linked with a particular class much later after the
compilation. This process is known as “Dynamic binding”. The selection of the
appropriate function is done dynamically at run time. The following diagram shows the
implementing the polymorphism concept in different ways.

Polymorphism

Compile Time Poly. Run time Poly.

Function overloading Operator overloading Virtual Functions

Function Over loading:


Function over loading is a logical method of calling several functions with different
arguments and data types that perform basically identical things by the same name. The
main advantages of using function overloading are:
- Eliminating the use of different function names for the same operation.
- Helps to understand, debug and grasp easily.
- Easy maintainability of the code
- Better understanding of the relation between the
program and the outside world.

Function overloading is an easy concept in C++. The compiler classifies the overloaded
function by its name and the number and type of arguments in the function declaration.
The function declaration and definition is essential for each function with the same
function name but with different arguments and data types.

Syn:

void funname( )
{

---------------
--------------
}

void funname(single arg)


{

---------------

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
20

--------------
}

void funname(multiple args)


{

---------------
--------------
}

Operator Overloading:
Operator over loading is one of the many existing features of C++ language. It is an
important technique that has enhanced the power of extensibility of C++. C++ permits to
add two several of user defined data type with the same syntax. That are applied to built-
in data types this means that c++ has the ability to provide the operators with a special
meaning for a data type. The mechanism of giving such special meaning an operator is
known as “Operator over loading”.

Operator over loading provides a flexible option for a creation of new definitions for
most of the C++ operators. Use of the functions and operator overloading techniques. We
can over load all the operators except the following operators.

1. Data member access operator .


2. Scope resolution Operator :: and :
3. Size of operator sizeof
4. Conditional Operator ? and :
5. Separator ,
6. Pre-processor #
7. Pointer Operator ->
8. Reference operator &
Syn :
returntype className :: operator symbol(args)
{
//Body of the fun. }
Ex:
void num :: operator +()
{
// body of fun.
}

When the return type is type of the value is returned by specified operation and symbol is
operator being over loaded. The symbol is preceded by the keyword operator. The
operator symbol is the function name.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
21

Rules:
1. The over loaded operator must have at least one variable. i.e. user defined data
type.
2. We can not change basic meaning of an operator.
3. Overloaded operators follow the syntax rules of original operator.
4. We can not use friend function to overload certain operators.
5. Binary and arithmetic operators must explicitly return a value.
6. new operator can’t be created only existing operator can be overloaded.

Virtual Functions:

C++ provides a solution to invoke the exact version of the member function. Which has
to be decided at runtime using virtual functions. They are the means by which functions
of the base class can be overridden by the functions of the derived class. The keyword
virtual provides a mechanism for defining the virtual functions when declaring the base
class member functions the keyword virtual is used with those functions which are to be
bound dynamically.

The syn. of defining a virtual function in a class is shown below.


class Sample
{
specifiers:
instance vars ;
public:
//over ridded method
virtual returntype funname(args)
{
// body of the fun
}
… … … … … … … ..
};

Virtual function should be defined in the public section of a class to realize its full
potential benefits. When such a declaration is made it always to be decide which function
to be used at runtime, based on the type of the object, pointed to by the base pointer,
rather than the type of the pointer.
Rules :
1. These functions must be members of sub classes
2. They can not be static members
3. They are accessed using pointers only.
4. A virtual function in a base class must be defined, even though it may not be used.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
22

Virtual Classes:
C++ supports important concept called virtual base classes to handle ambiguity caused
due to the multipath inheritance. It is achieved by making the common base class as a
virtual base class while declaring the director intermediate classes as shown below.

Syn:
class A
{
………
public:
//member function
void func()
{
… … … … ..
}
};

class B : virtual public A


{
…………
};

class C : virtual public A


{
…….
};

class D: public B, public C


{
… … ..
};

consider, the statement


od.func();

where od is the object of the class D and invokes the func() defined in the class A. If the
key word virtual does not exist in the declaration of classes B and C.

Pure virtual functions:


It is normal practice to declare a function virtual function inside a base class and redefine
it in the derived classes. The function inside the base class is seldom used for performing
any task. It only serves as a placeholder. Such functions are called "do nothing"
functions.

syn:
virtual returntype funname( ) = 0 ;
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
23

A pure virtual function is a function declared in a base class that has no definition relative
to the base class. In such cases, the compiler required each derived class to either define
the function or re-declare it as a pure virtual function. A class containing pure virtual
functions can not be used to declare any objects of its own.

Concrete Class:
It is a class, which can be instantiated. Any class with no pure virtual functions is known
as “Concrete class”.

Abstract Class:
Abstract class is one that is not used to create objects. Abstract class is designed only to
act as a base class to be inherited by other class. It is a design concept in program
development and provides a base upon which other classes may be built.

//Develop an interactive bank application by implementing the pure virtual functions


given in the class Bank.

#include <iostream.h>
#include <conio.h>
#include <process.h>

class Bank
{
public:
//pure virtual functions
virtual void read( )=0;
virtual void deposit( )=0;
virtual void draw( )=0;
virtual void balance( )=0;
};

class Bankdemo : public Bank


{
private:
int accno;
char accname[20], acctype[10];
float bal;
public:
void read( )
{
cout<<”\nEnter account no, name , type and balance :”;
cin>>accno>>accname>>acctype>>bal;

if(bal<500)
{
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
24

cout<<”\nInitial deposit should not be less than Rs.500/- “;


cout<<”… .Press any key … .:”;
getch();
exit(0);
}
else
{
cout<<”Account created”;
getch( );
}

void deposit( )
{
float amt;
cout<<”\nEnter amount to deposit :”;
cin>>amt;

bal=bal+amt;
cout<<”\nAccount updated”;
cout<<”\n… .Press any key … . :”;
getch( );
}

void draw( )
{
float amt;
cout<<”Enter amount to draw :”;
cin>>amt;

if( amt<=(bal-500))
{
bal=bal-amt;
cout<<”\n Account updated”;
cout<<”\n… Press any key … .:”;
getch( );
}
else
{
cout<<”\n Sorry, you can withdraw only Rs. :”<<bal-500;
getch( );
}
}

void balance( )
{

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
25

cout<<”\nLedger balance :”<<bal;


cout<<”\n Available balance :”<<bal-500;
getch( );
}
};

void main( )
{
int ch=0;
bankdemo b;
clrscr( );
b.read( );

while(ch!=0)
{
cout<<”\nBanking\n1.Deposit\n2.Withdraw\n3.Balance\n4.Exit\n\n”;
cout<<”Choose any option ..:”;
cin>>ch;

switch(ch)
{
case 1: b.deposit(); break;

case 2: b.draw(); break;

case 3: b.balance();break;

case 4: cout<<”\n\nAccount Updated”;


cout<<”\nPress any key to exit “;

default: cout<<”\n invalid choice”;


getch( );

} //end of switch
} // end of while
} //end of main

Templates
Template is a generic data type. Creating the user defend data type. Using templates
overcome the function overloading problem. Generally, it is used for functional
programming.

Templates are two types. Those are,


i) Function templates ii) class templates
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
26

syn :
template <class tempname, … >

Ex: template <class T>

Here, template is a keyword and T is the name of the user-defined data type
(class).

Syn. of Fun. Template Defintion :

returntype funname(templatename args)


{
------------------
------------------
}

Ex : void hello( T a )
{
---------
--------
}

Syn. of Class Template Defintion :

class Sample
{
specifier:
//data members
Template vars;
Specifier:
// member functions
returntype funname(templatename args)
{
------------------
------------------
}
};

//object creation
Sample <datatype> objname;

Here, <datatype> ? primitives or classes

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
27

Exception Handling
Def: The errors are called "Exceptions". The Process of dealing with exceptions in a
program is called "Exception handling".
- Run time errors occurred in a program is called “Exceptions”.

Errors are always likely to occur and it is important to provide means to handle them.
There are two basic kinds of errors.
1. Compile time exceptions: The errors that occur during compilation of a program.
2. Run time exceptions: The errors that occur during execution of a program.

Sources of errors:
Syntax errors: Typing errors

Device errors: These errors occur when there are problems with devices such as printers,
improperly connected devices, printer’s exit of papers etc.

Physical errors: These errors occur with respect to physical entities or capacities.
Ex. space is not available on disks or main memory.

Code errors: Errors that occur when logic is wrong.


Ex. Locating non-existing files, Data structures etc.

The Exception handling mechanism transfers the control from where the error occurred to
an exception handler that can deal with the exceptions.

Syn:
try
{
//code which could throw an exception
}

catch ( exceptiontype )
{
// Handle the exception here
}

Notes:
- Does not place any executable statement in between try block and
catch blocks.
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
28

- A try block can follows any no. of catch blocks.


- A try block contains unexpected code. If any exception is
- occurred in that block, which exception is send to their corresponding
catch block using throw statement.
Here, try, catch and throw words are keywords.

I /O Streams
Stream : Flow of bytes or characters through a buffer is called a “Stream”.

There are two types’streams:


1. Input Stream: Reads data from a source.
2. Output Stream: Writes / displays data to a target.

Files
Def : Collection of data / information stored in a particular device permanently. That is
called a ‘File’.
There are two streams in files.
1. Input file stream : Reads data from a file is said to be ‘input file stream’.
2. Ouput file stream : Writes / stores data to a file is said to be ‘output
file stream’.

File names are 2 types:


i. Primary filename : It is designed by user. It’s max. length is 8 chars
only.
ii. Extension name : It is allotted by its application by default. It can
allow up to 3 chars.

Note: Primary filename and extension names are separated by a dot.


- Any file can follow 8.3 rule.

Eg.
Koti-eswhar.doc
Myfile.txt
Stddata.xls
Total.c
Palindrome.cpp
Myweb.java etc.

Types of Files :
There are many types in files.
- Text files [ The files, which are created in Notepad application only] : It can
allow only characters.
- Document files [The files, which are created in Ms-word application etc]: It can
allow text / diagrams/ pics./ animations / tables etc.
---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
29

- Data base files [The files, which are created in MS-Access application etc.] etc.

Data Base Management System [DBMS]:


It is an application software. It can manage the tables / files in a DB.
Data Base [DB]:
It is a logical container. It can store data in the form tables, functions, files etc.
Table:
The data is stored in the form of rows and columns.
Or
Collection of related records is called a Table.

Row / Record :
The collection of (attributes) fields in a table.
A row of information represents a record in a table / file.
Field:
An individual data item (column) in the table is called a field.

Advantages of files :
1. To store the data permanently.
2. Easy to retrieve / modify / delete / search required data from a file
3. Provide security to a file etc.

Operations on Files :
- Create a new file.
- Open an existing file.
- Close an existing file.
- Store data into a file.
- Append (Add) new data to the existing file
- Retrieve / read data from a file.
- Modify / update data from in a file
- Search required data from a file.
- Delete data from a file.
- Copy a file to another file.
- Merge two files.
- Remove a file from disc (source).
- Rename a file etc.

Functions used in Files :


The following functions are defined in the header file ‘iostream.h’.

- open() :
It can be used for creating a new file or opening an existing file.

Syn:
filestream fileobj;

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
30

fileobj.open (filename, mode) ;

- close():
It can be used for closing opened files.
Every opened file must be closed.
Syn:
fileobj.close ();

- get():
It reads a single character from a file.
Syn:
fileobj.get(charvar);

-put ( ):
It stores a single character into a file.
Syn:
fileobj.put (var);

- getline():
It reads a string from a file.
Syn.
fileobj.getline( var, size);

-eof( ):
It represents File end of File.
Syn.
fileobj. eof()

-write():
It can stores / displays details of an object into a file.
Syn. fileobj. write ((char*) &obj, sizeof(obj)) ;

-read():
It can reads / retrieves details of an object from a file.
Syn.
fileobj. read ((char*) &obj, sizeof(obj)) ;

-rename ( ):
To renaming a file. That means to change the name of the file.
Syn.
rename (oldname, newname) ;
-remove():
It can remove a file from disc.
Syn.
remove (filename);

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
31

-seekg():
To get the position of the control in the file.
Syn.
seekg(position, ios::beg/end) ;

-seekp():
To put the control to the specified position in the file.
Syn.
seekp(position, ios::beg/end) ;

File Opening Modes


There are some modes for opening a file. Those are,

Mode Meaning
ios :: in Reading data from a file
ios :: out Writing data into a file
Ios :: app Appending data to a file
Ios :: binary Reading / writing data from / to a file.
Modification is allowed.
Ios :: err It displays an error msg. when a specified
file is not exist in the local disc.
Ios :: noreplace / nocreate Does over write / not over write the
modified file.

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.
32

---------------------------------------------------------------------------------------------------------------------------------
V I S I X T e c h n o l o g i e s, # 1 0 8 , A n n a p u r n a B l o c k , A d i t y a E n c l a v e , A m e e r p e t , H Y D .
Phone : 66361220.

Potrebbero piacerti anche