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

C++ With Examples

Procedure Oriented Programming (POP) employs a top-down approach where problems are broken down into a sequence of tasks performed by functions. This allows data to move freely between functions, which can introduce bugs. Object Oriented Programming (OOP) was developed to overcome these drawbacks by encapsulating data within classes and restricting access to only member functions, thereby reducing bugs. OOP employs concepts like classes, objects, inheritance and polymorphism. Classes act as templates for creating objects that combine data and code, and inheritance allows classes to share properties.

Uploaded by

Krishna Gurjar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

C++ With Examples

Procedure Oriented Programming (POP) employs a top-down approach where problems are broken down into a sequence of tasks performed by functions. This allows data to move freely between functions, which can introduce bugs. Object Oriented Programming (OOP) was developed to overcome these drawbacks by encapsulating data within classes and restricting access to only member functions, thereby reducing bugs. OOP employs concepts like classes, objects, inheritance and polymorphism. Classes act as templates for creating objects that combine data and code, and inheritance allows classes to share properties.

Uploaded by

Krishna Gurjar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Procedure Oriented Programming: - (POP)

Conventional programming using high-level languages such as


COBOL, FORTRAN & C, is commonly known as procedure oriented
programming (POP). In the procedure – oriented approach, the
problem viewed as a sequence of things to be done such as reading,
calculating & printing. A number of functions are written to accomplish
then tasks. The primary focus is on functions. A typical program
structure for procedural programming is shown in fig. The technique of
hierarchal decomposition has been used to specify the tasks to be
completed for solving a problem.

Main Program

Function -1 Function -2 Function -3

Function - 4 Function -5

Function -6 Function -7 Function -8

Some characteristics of procedure - oriented programming are: -


1- Emphasis is on doing things (algorithms).
2- Large programs are divided into smaller programs known as
functions.
3- Most of the functions share global data.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
4-
Data merely open around the system from function to
function.
5- Functions transform data from one form to another.
6- Employs top- down approach in program design.
Drawback of procedure- oriented programming
1- In a multi function program, many important data items are
placed as global so that may be accessed by all the functions such
function may have its own local data figure 1.5 shows the relationship
of data & functions in a procedure- oriented program.

Global data Global data

Function –3 Function –3 Function –3


Local data Local data Local data

Relationship of data and functions in procedural programming

Global data are moving weak to a chance that it may be changed


by a function. In a large program it is very difficult to identify what
data is used by which function in case we need to revise on external
data structure, we also need to revise all functions that access the
data this provides an opportunity for bugs to creep it.
2- Another serious drawback with the procedural approach is that it
does not model real world problems very well this is because functions
are action oriented & do not really correspond to the elements of the
problem.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
POP has two major drawbacks: -
1- Data move freely around the program & therefore weak to
changes caused by any function in the program.
2- It does not model very well the seal- world
Object – Oriented Programming (OOP): -
OOP was invented to overcome the drawbacks of the POP. It
employs the bottom up programming approach. It treats data as a
critical element in the program development & does not allow it to flow
feely around the system. It tries data more closely to the functions
that operate on it in a data structure called class. This feature is called
data encapsulation.
POP: -POP employs top-down programming approach where problem
is viewed as a sequence of tasks to be performed. A number of
functions are written to implement these tasks.
Basic concept of object- oriented programming (OOP): -
The basic concept of object-oriented programming is as follows
- Objects
- Class
- Data abstraction & encapsulation
- Inheritance
- Polymorphism
- Dynamic binding
Message passing
Object is nothing but has its own property & methods. In
programming languages, objects are the basic run- time entities in an
object-oriented system.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
When a program is executed, the objects interact by sending
messages to another object. If “customer” & “account” are two objects
in a program, then the customer object may send a massage to the
account object requesting for the bank balance.
Each object contains data, & code to manipulate the data. Objects can
interact without having to know details of each other data & code. It is
sufficient to know the type of massage accepted & the type of
response returned by the objects. Following two notations that are
popularly used in object oriented analysis & design.

Object : -
EMPLOYEE DATA
Name Total
Date of birth Salary
Salary Employee

FUNCTIONS Display
Total Salary
Display

Two ways of representing an object


Classes: -
A class is a collection of properties & methods. Thus a class is a
collection of objects of similar type. We can say class is templates for
creating objects. For example mango and apple are members of the
class fruit. Classes are user – defined data types & behave like the
fruit in types of a programming language. The system used to create
an object is different than the system used to create an integers object
in C. If fruit has been declared as a class, then the statement.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Fruit mango;
Will create an object mango belonging to the class fruit.

Data Abstraction & encapsulation


The wrapping up of data & functions into a single unit is known
as encapsulation. Data encapsulation is not the striking feature of a
class. The data is not accessible to the out side world, & only throe
functions which are wrapped in the class can access it. These functions
provide the interface between the object’s data & the program. This
insulation of the data from direct access by the program is called data
hiding or information hiding.
Abstraction refers to the act of representing essential features
without including the background details or explanation. Class uses
concept of abstraction & are defined as a list of abstract attributes
such as age, weight, height & function to operate on these attribute.
They encapsulate all the objects that are to be created. The attributes
are sometimes called data members because they hold information the
functions that operate on these data are sometimes called methods or
member functions.
Since the class uses the concept of data abstraction they are
known as Abstract Data Type (ADT)
INHERITANCE: -
Inheritance is the process by which objects of one class acquire
the properties of objects of another class. It supports the concept of
hierarchical classification for ex. The bird robin is a part of the class
flying bird, which is again a part of the class bird the principle behind

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
this most of division is that each derived class shares common
chrematistics with the class from which it is derived as illustrated in

Bird
Attribute
Feathers
Lay eggs

Flying Bird Non-Flying Bird


Attribute Attribute
…………. …………
…………. …………

Robin Swallow
Penguin Kiwi
Attribute Attribute
Attribute Attribute
………. ……….
………. ……….
………. ……….
………. ……….

In OOP, the concept of inheritance provides the idea reusability.


This means that we can add additional features to an existing class
without modifying it. This is possible by deriving a new class from the
existing one the new class will have the combined features of both the
new class will have the combined features of both the classes.
The old class in referred to as the base class & the new one is
called the derived class or sub class. The derived class inherits some
or all of the properties from the base class. A class can also inherit
properties from more than one class or from more than one level.
There are five types of inheritance.
1- Single inheritance.
2- Multiple inheritance.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
3- Hierarchical inheritance.
4- Multiple inheritance.
5- Hybrid inheritance.

A derived class with only one base class is called single


inheritance & one with several base classes is called multiple
inheritance. On the other hand more than one class may inherit
properties of one class. This is known as hierarchical inheritance. The
mechanism of deriving a class from another derived class is known as
multilevel inheritance. The combination of multiple inheritance &
multilevel inheritance is the hybrid inheritance.
Polymorphism: -
Polymorphism is another important OOP concept. Polymorphism
means the ability to take more than one form. It means one name
with multiple forms. It allows us to have more than one function with
the same name in a program. It also allows overloading of operators
so that an operator can exhibit different behaviors in different
instances.
For example, consider the operation of addition. For addition of
two numbers the operator will generate a sum. If the operands are
strings, then the operator would produce a third string by
concatenation.
Operator overloading: - The process of making an operator to
exhibit different behaviors in different instances is known as operator
overloading.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Figure illustrates that a single function name can be used to
handle different number & particular word having several different
meanings depending on the context.

Shape
Draw ()

Circle object Box Object Triangle Object


Draw (circle) Draw (box) Draw (triangle)

Function overloading: - using a single function name to perform


different types of tasks is knows as function overloading.
Dynamic Binding: -
Dynamic binding means that the code associated with a given
procedure is not known until the time of the call at run – time.
Message passing: - An object-oriented program consists of a set of
objects that communicate with each other. The process of
programming in an object – oriented language involves the following
steps.
1- Creating classes that define objects & there behaviors.
2- Creating objects from class definitions.
3- Establishing communication among objects.
Objects communicate with another object by sending & receiving
information much the same way as people pass messages to one
another.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Messages for object is a request for execution of a procedure &
therefore will invoke a function in the receiving object that generates
the desired result. Message passing involves specifying the name of
the object, the name of the function (Message) & the information to be
sent.

Employee salary (name);

Object Information
Message

Objects have a life cycle. They can be created & destroyed


communication with object is feasible as long as it is alive.
Benefits of OOP
OOP offers several benefits to the Programmers productivity, better
quality of software & lesser maintenance cost. The principal
advantages are.
* By inheritance, we can eliminate redundant code & extend the
use of existing Classes.
* We can build programs from the standard working modules that
communicate with one another, rather than having to start
writing the code from scratch. This leads to saving of
development time & higher productivity.
* The principle of data hiding helps the programmer to build
secure programs that cannot invade by code in other parts of the
program.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
* It is possible to have multiple instances of an object to co exist
without any interference.
* The data centered design approach enables us to capture more
details of a model in implementable form
* Object - oriented systems can be easily upgraded from small to
large systems.
* Message passing techniques for communication between objects
makes the interface descriptions with external systems.
* Software complexity can be easily managed.
C++ is an object – oriented programming language. It was
developed by Stroustrup at AT &T Bell Laboratories in early 1980’s.
Input Operator: -The operator >> is known as extraction or get from
operator it extracts (or takes) the value from the keyboard & assigns it
to the variable on its right.
Constructors: - A constructor is a “special” member function
whose task is to initialize the objects of its class. It is special because
its name is the same as the class name. The constructor is invoked
whenever on object of its associated class is created. It is called
constructor because it constructs the values of data members of the
class. Constructor is declared & defined as follows:
// Class with a constructor
Class A
{
Public:
A (void) ;//constructor declared
…………..
…………..

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
}
A :: A (void) // constructor defined
{cout<< “This Is A Constructor”;}
A constructor that accepts no parameters is called the default
constructor. The default constructor for classes A in A: A (). If no such
constructor is defined, then the complier supplies a default
constructor. Therefore statements such as.
A a;
Invokes the default constructor of the compiles to create the object a.
The constructor functions have some special characteristics. They are
as follows: -
 They should be declared in the public section.
 They are invoked automatically where the objects are created.
 They do not have return types, not even void. Therefore they
cannot return Values.
 They cannot be inherited, though a derived class can call the
base class constructor.
 Like other C+ + functions, they can have default arguments.
 Constructor cannot be virtual.
 We cannot refer to their addresses.
 An object with a constructor (or detractor) cannot be used as a
member of a union.
 They make implicit calls to the operators new & delete when
memory allocation is required.
Remember, when a constructor is declared for a class,
initialization of the class objects becomes compulsory.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Memory Allocation for objects: -
The memory space for the objects is allocated when they are
declared. Space for member variables is allocated separately for each
objects, is allocated separately for each object, but no separate space
is allocated for member functions.
Parameterized Constructors: -
The constructors that can take arguments as called
parameterized constructors. The constructor integer () may be
modified to take arguments as shown below.
Class integer
{
int m, n,
Public:
integer (int x, int y) //parameterized constructor//
{
m = x; n= y;
}
};
Overloaded constructors: -
When there are two or more constructors with the same name
abc (), we say the constructor is overloaded which of the constructors
is executed when an object is created depends on how many
arguments are used in the definition.
#include <iostream. h>
#include <conio. h>
Class abc
{ int a,b;

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
public :
abc () {a=5; b=7;}
abc (int a1,int b1) { a=a1; b=b1 }
void display() { cout <<"a="<<a<< "\n"; cout <<"b="<<b<< "\n" }
}
Polymorphism & Overloading: -
Using operator or functions in different ways, depending on what
they are operating is called polymorphism (one thing with several
distinct forms). When an existing operator, such as + or = are given
the capability to operate on different data types, it is said to be
overloaded. Overloading is a kind of polymorphism. It is also an
important feature of oops.
Operator overloading: - To define an additional task to an operator,
we must specify that is means in relation to the class to which the
operator is applied. This is done with the help of a special function,
called operator function, which describes the task the general form of
an operator function is:
return type class name: :operator op(arglist)
{ function body } // task defined
Where return type is the value returned by the specified
operator function & op is the operator being overloaded. The op is
preceded by the keyword operator. Operator op is the function name.
Operator function must be either function (non static) or friend
function. A basic difference between them is that a friend function will
have only one argument for unary operators & two for binary operator
while a member function has no arguments for unary operators & only
one for binary operators.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
The process of overloading involves the following steps: -
1- Create a class that defines the data type that is to be used in the
overloading operation.
2- Declare the operator function operator op () in the public part of
the class. It may be either a member function a friend function.
3- Define the operator function that implement the required
operations.
[For Examples of overloading refer classroom examples]
Inline function: -
Inline is just a request to the compiler functions are used in
programs to some memory space. Every time a function is called it
takes a lot of extra time in executing a series of instructions for tasks
such as jumping to the function, saving registers, washing arguments
into the stack & returning to the calling function. It reduces the
execution speed of a program. To eliminate the cost of calls to small
functions, C+ + proposes a new feature called inline function. An inline
function is a function that is expanded in line when it is invoked that is
the compiler replaces the function call with the corresponding function
code the inline functions are defined as follows.
inline function _name(formal parameter list)
{ Function body }
Disadvantage: -
1- The functions are made inline when they are small enough to
be defined in one or two lines.
2- Some of the situations where inline expansion may not work
are: -

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
(I) For functions returning values, if a loop, a switch or a
goto exists.
(II) For functions not returning values, if a return statement
exists.
(III) If functions contain static variables.
(IV) If inline functions are recursive.
Advantage: -
Inline expansion makes a program faster because the overhead
of a function call & return is eliminated. For Ex:
inline int mul (int x, int y )
{ return (x * y); }
void main ()
{ int a =12, b= 6;
cout << mul (a,b); getch ();}
Static Data Members: -
A static member variable has following special properties :
1- It is initialized to zero when the first object of its class is
created. No other initialization is permitted.
2- Only one copy of that member is created for the entire class &
is shared by all the objects of that class. No matter how many
objects are created.
3- It is visible only within the class, but its lifetime is the entire
program.
Static variables are normally used to maintain values
common to the entire class.
Friend functions: - To make an outside function “friendly”, we have
to simply declare this function as a friend of the class.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Class ABC {
-----
Public:
-----
Friend void xyz (void;) //declaration };
The keyword friend should precede the function declaration. The
function is defined elsewhere in the program. The function definition
does not use either the keyword friend or the scope operator( :: ).The
function which are declared with the keyword friend is known as friend
function. A function can be declared as a friend in any member of
classes. A friend function has full rights to access private members of
the class.
A friend function has following special characteristics :
1- It is not in the scope of the class to which it has been
declared as friend.
2- Since it is not in the scope of the class, it cannot be called
using the objects of that class.
3- It can be invoked like a normal function without the help of
any object.
4- It can be declared either in the public or the private part of a
class without affecting its meaning.
5- Usually, it has the objects as arguments.
[For Examples of Friend Function refer classroom examples]
Function overloading: -
Overloading refers to the use of the some thing for different
purposes. Similarly, we can use the same function name to create

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
functions that perform a variety of different tasks. This is known as
function polymorphism in OPPS.
An overloaded function is actually a group of function with the
same name which of them is executed when the function is called
depends on the type & number of arguments supplied in the function
calling.
For Ex:
void main()
{int add(int, int); //prototype of function with 2 parameter
int add(int, int, int); // prototype of function with 3 parameter
int c=add(10,40); cout<<c;
int d=add(20,30,40); cout<<d; getch(); }
int add(int x,int y) { return(x+y); } //function with 2 parameter
int add(int x,int y,int z){return(x+y+z); }//function with 2 parameter
Default Parameter(Arguments) : -
When function is called without specifying all of its arguments, at
that time the function can be assigned as default values to the
parameter, which do not have a matching argument in the function
call. Default values are specified when the function is declared. The
compiler looks at the prototype to see haw many arguments a function
uses & alerts the program for possible default values.
Advantages of providing the default arguments are:-
1- We can use default arguments to add new parameters to the
existing functions.
2- Default arguments can be used to combine similar function
into one.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
3- Default arguments are useful in situations where some
arguments always have the some value.
4- It also provides a greater flexibility to the programmers.

Default arguments
# include <isostream h>
# include <conic .h >

Float amount (float principal, int period, float rate=0.15)


main ()
{
Cont <<amount (500, 7) <<”in”;
getch ();
Inheritance: -
Inheritance is the process of creating new classes, called derived
classes, from existing or base class the derived class inherits all the
capabilities of base class but can add embellishments & refinements of
its own the base class in unchanged by this process.
The most important advantage of inheritance most
importantly it permits code reusability. Reusability in the sense that as
we know that a child comes from a father & child having all the feature
of his father i.e. child in reusing the features of his father. Similarly
derived classes will reuse the features of base classes. The inheritance
relationship is shown in figure

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
features A
features B
features C

Derived class

features D } Defined in derived class


features A

}
Defined in base class
features B But accerible from
Derived class
features C

Defining derived classes: -


A derived class can define by specifying its relationship with the
base class in addition to its own details. The general form of defining a
derived class is.

* When the base class is publicly inherited, inherited, public


members of the base class becomes public member of the derived
class & therefore the public members are accessible to the objects of
the derived class.

* When a base class in privately inherited by a derived class,


public members of the base class become private members of the
derived class & therefore the public members of the base class can
only be accessed by the member functions of the derived class. They
are inaccessible to the objects of the derived class. Remember, its own

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
objects using the dot operator can access a public member of a class.
The result is that no member of the base class is accessible to the
objects of the derived class.

In both the cases, the private members are not inherited &
therefore, the private members of a base class will never become the
members of its derived class.
Single inheritance: -
Single inheritance: public
Class mores //Base class
{
Public:
int h, e, m,
Void getdata ();
{;
class total: public marks //Derived class
{
int, total;
Multilevel Inheritance: -
It is not uncommon that a class is derived for another derived
class. When a class is derived from other class & that is also derived
from another class it is called multilevel inheritance. The class A server
as a base class for the derived class B , which in turn serves as a base
class to the derived class c the class b in known as intermediate base
class since it provider a link for the inheritance between A& C. the
chain ABC is fen own as inheritance path.
A derived class with multilevel inheritance is declare as follows:

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Class A{- - - - - }; // Base class
Class B Public A {- - - - - }; // B derived from A
Class C Public B {- - - - - }; //C derived from B
The process can be extended to any member of levels

Base Class A Grandfather

Intermediate Father
B
base Class

Derived class C Child

Multilevel inheritance
Multilevel inheritance
# include <iostream . h>
# include <conies. h>
class details
{
public;
total = h + e +m;
{
void total :: display ()
{
cout <<roll no <<name<< “in”;
cout <<h<<e<<m<< “in”;
cout <<total << “in”;
{

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
void main ()
{
total t;
t get details ();
t get marks ();
t calculate ();
t display ();
getch ();
}
Multiple inheritance: -
A class can be derived from move than one base class. This is
called multiple inheritance.
A class can inherit the attributes of two or more classes are
shown in the figure. This is known as multiple inheritance. Multiple
inheritance allows us to combine the features of several existing
classes as a starting pint for defining new class. It is like a child
inheriting the physical features of one parent & the intelligence of
another.

Base class Base class B

Doured class C

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Pointers: -
Pointer variables are the one, which can store the adders of
normal variable.
Addresses & pointers: -
Every byte in the computers memory has an address. Addresses
are numbers start at o & go up for there –1, 2, 3 & so on.
Our program, when it is loaded into memory occupies a certain a
certain range of address. That means that every variable & every
function in out program starts at a particular address.
The address of operation &
We can find out the address occupied by a variable by using the
adders of operation & here’s shot program that demonstrates haw to
do this.
# include <iostream. h>
# include <conio . h>
void main ()
{
int var 1 = 11;
int var 2 = 22;
int var 3 = 33;
Cout <<endl << & var 1,
<<endl; << & var2,
<<endl; << & var3,
}

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Pointer Variables: -
A variable that holds on address value in called a pointer
variable, a pointer.
Pointer to objects: -
A pointer can point to an object created by a class consider the
following statement;
XYZ X;
Where xyz is a class & x is an object defined to be of type xyz.
Similarly we can define a pointer & of type xyz as follow.
Xyz *p;
Object pointer is useful in creating objects at rum time. We can
also use an object pointer to access the public members of an object.
Consider a class xyz defined as follows:
Class xyz
{
class name [30];
int age;
public
void getdata (void);
void display (void);
{
Void xyz :: getdata (void)
{
cout <<enter name:”;
cin >> name;
cout << enter age :”;
cin >>age;

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
{
void xyz :: display (void)
cont << “\n name: <<name;
cont<< “\n age : “ <<age;
{
void main ()
{
xyz x; //Let us declare an xyz variable x & pointer & for
xyz *p = & p x ; // The pointer & is initialized with the adder.
P – getdata ();
P – display ();
geteh ();
}
We can refer to the member function of xyz in two ways, one by
using the dot operation & the object, & another by using the arrow
operator & the object. The statements.
X. getdata ();
X. display ();
Ore equivalent to
P – getdata ();
P – display ();
Since * p in an alias of x, we can also use the following method
(*p). display ();
We can use pointers not only to the base objects but also to the
object of a base class are type – compatible with pointers to objects of
a derived class. Therefore, a single pointer variable can be made to
point to objects belonging to different classes. For example, it B in a

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
base class & D is a derived class from B then a pointer declared as a
pointer to B can also be a pointer to D. consider the following
declarations:
B*cptr; // pointer to class B type variable.
B d; // base object
D d; // derived object
Cptr = & t; // cptr points to object to
We can make cptr to pint to the object d as follow
Cptr = & st; // cptr pints to object d
This is perfectly valid because d in an object derived for the class B
# include <iostream.h>
# include <conio. h>
class fast
{
Public: -
Char name [20];
Void getdata (void);
{
void fast :: getdata (void)
{
cont << “enter name”;
cin >> name;
{
class second : public fist
{
public:
void display ();

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Ptr
Base
& Derv 1
Show ()
Ptr->show ()

Derv1
Show ()
Ptr
& Derv 2

Ptr->show ()
Derv2
Show ()

Virtual Functions: -
As we have discovered that a base pointer ever when if is made
to contain the address of a derived class, always executes the function
in the base class the function name are some in both base & decried
class. If we want to access or call the function, which is in the derived
class, then we use the concept virtual functions.
Virtual means existing in effect but not in reality A virtual
function, then, is one that does not really exist but nonetheless
appears read to some parts of a program.
When we use the same function name in both the bas & derived
class, the function in base class is declared as virtual using the
keyword initial preceding its manual declaration.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Rules for Virtual Function: -
When virtual function are created for implementing data binding
we should observes some basic rules that satisfy the compiler
requirements:
1- The virtual functions must be members of name class.
2- They cannot be static members.
3- They are accessed by using object pointers.
4- A virtual function can be a find of another class
5- A virtual function in a base class must be defined even though
if may not be used.
6- The prototypes of the base class version of a virtual function
& all the derived class versions must be identical. If two
functions with the same name have different prototype, c + +
considers then as overloaded functions, & the virtual function
mechanism is inroad.
7- We cannot have virtual constructors, but we can have virtual
destructors.
8- While a base pointer can point to any type of the derived
object, the reverse is not true. That is to say, we cannot use
a pointer to a derived class to access an object of the base
type.
9- When a lose pointer points to a derived class, incrementing or
decrementing it will not make it to point to the next object f
the derived class. It is incremented or decremented only
relative to its base type. Therefore, we should not class this
method to move the pointer to the next object

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
10- It a virtual function is defined in the base class it need not be
necessarily redefined in the derived class. In such cases, will
invoke the base function.
Pure Virtual Functions: -
It pure virtual function is a virtual function with no body. There
is no need for the base class version of the particular function; we only
use the version of the function in the derived class. When this is true,
the body of the virtual function in the box class can be removed, & the
notation =o added to the function declaration.
# include <iostream. h>
# include <conio.h>
class fist
{
Public;
Char name [20];
Void getdata (void);
Virtual void display () =o;
{
void first:: getdata ()
{
cont <<enter the name:”;
cin >>name;
class second : public fist
}

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
1- It the pointer of base class is pointing to the derived class &
having function name same in both the bas & derived class
then in this case the member functions of the base class will
be called.
2- It we want to call the function of derived by the base class
pointer then we make the member virtual function of the
base, which is also having the same name that of member
function, is derived.
3- It we are haring a function which does nothing & we don’t
want to define that function we just make that function pure
virtual function by adding the notation =o to the function
declaration.
Templates
Generic Variables: -
Generic variables are these variables, which accepts any type of
value whether it is int float & double type values etc.
Templates: -
Templates are a concept, which makes the program and generic.
Generic Programming: -
Generic Programming is an approach where generic types are
used as parameters in algorithms so that they work for a variety of
suitable data types & data structures.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Class Templates: -
As me that we want to define xyz class with the data type as
parameters & them use this class to create a xyz of defining a new
class every time. The template mechanism enables us to achieve this
goal. The general format of a class template is.
Template <class T>
Class class name
{
//……………..
// class member specification
//with anonymous type T
//whenever appropriate
//……………..
};
The following table illustrates this
Qualifier Private Protected Public
Private Private* Private Private
Protected Private* Protected Protected
Public Private* Protected Public
Note: -
Private members of the base class are not accessible from with
the derived class, whatever be the type of inheritance. They just add
to the derived class member list & can be accessed any through the
inherited public or protected member of the base class.

The class template definition is very similar to an ordinary class


definition except the prefix template < class T> & the use of type T.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
this prefix tells the compiler that we are going to declare a template &
use t as a type name is the declaration. Thus, xyz has become a
parameterized class with the type T as any data type may substitute
its parameterized T. Including the user defined types now, we can
create xyz for holding different data types.

Example: -
XYZ <int>a (10);
XYZ <float> b (10.2);
A class created form a class template is called a template class.
Example of class Template
#include <iostream. h>
#include <conio. h>
template <class T1 class T2>
class xyz
{
T1 x;
T2 y;
Public :
Xyz ( T 1 a, T2b)
{
x=a;
y=b;
cout <<x<< “and”<<y<<in,
{
};
Void main ()

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
{
clrscr ()
xyz <float, int> xyz 1 (1.23, 123);
xyz <int, char> xyz 2 (100, ‘w’);
xyz <int, int> xyz 3 (10, 20);
xyz <float, float > xyz 4 (12.20, 20.12);
xyz <float, char> xyz 5 (10.20, ‘w’);
xyz <char, char> xyz 6 (‘p’, ‘p’);
getch ();
}
Function Templates: -
To crate a family of function with different argument types then
we use function templates. The general format of a function template
is.
Template <class T>
Return type function me (arguments of type T)
{
//………………
//Body of function
//With type T
//wherever appropriate
//……………….
}
Example of Function Template
# include <iostream h>
# include <conio .h>
template <class t>

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Difference between structure or keyword struct & class or
keyword class.
Actually C++ is considered to be & adapted as a superset of c
language means it has to support & inherit all the features of c
language structures is one of the features of c but in c it is not possible
to provide access specifies to members & define functions as
members of structure.
The only practical difference between a structure & a class in c+
+ is that if you don’t specify any access specifies in a class all
members will be private by default whereas in structure, we didn’t
define any access specifies & we were able to access all members of
the structure. It means all members of structure are public by default
if not stated others.
# include <iostream. h>
# include <conio. h>
int count =o;
class alpha
{
public;
alpla ()
{
count + +;
cont <<” \n no of object created” <<count;
{
alpha ( )
{
cont <<”\n no of object destroyed” <<count;

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
count - - ;
}
};
int main ()
cout << “\n \n ENTER MAIN \n:”
alpha A1, A2, A3, A4;
{
cout<< “\n \n ENTER BLOCK 1 \n:”
alpha 45;
{
{
cout <<“\n \n ENTER BLOCK 2 \n:”
alpha A6;
}
Exception handling: - An exception is an unusual event that happens
in a program under certain circusnstive, which is beyond the control of
the program.
Exception: -
Exception as the name tells is an exceptional unforeseen,
unpredictable condition that may occur in a program lading to an error
e.g. attempt to divide by zero, typing a character when input is being
taken for an integer or other numeric type can create errors & this
kind of error cant be predicted or solved at compile time or while
designing the program. Exceptions are conditions, which are non-
predictable & can accuser at run – time.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Basics of exception Handling: -
An error handing code performs the following tasks;
1- Find the problem (hit the exception)
2- Inform that an error has accrued (throw the exception)
3- Receive the error intonation (catch the exception).
4- Take coactive actions (handle the exception)
Exception Handling Mechanism: -
C++ exception handling mechanism built upon three keywords
namely, tries, throw & catch. The keyword try is used to preface a
block of statements which any generate exceptions. This block of
statement is known as fry block. When an exception is detected, it is
throws using a throw statement in the try block.
A catch defined by the keyboard catch ‘catches’ the exception
‘thrown’ by the throw statement in the by block & handles it
appropriately. The relationship is shown in the below fig.

try block

Detects and throws


an exception
Exception
object
catch block
catches and handles
the exception

Fig: Try block throwing exception

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
The catch block that catches an exception must immediately
follow the try block that throws the exception. The general form of
two blocks are as follows:
.....
.....
try
{
.....
throw exception; //Block of statements which detects
..... // & throws an exception
.....
}
catch(type arg) //Catches exception
{
.....
..... // Block of statements that
..... // handles the exception
.....
}
.....
.....
When the try block throw an exception, the program control
leaves the try block & enters the catch statement of the catch. Note
that exceptions are objects used to transmit information about a
problem. If the type of object thrown matches the arg type in the
catch statement, then catch block is executed for handling the
exception. If they do not match, the program is aborted with the help

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
of the abort () function, which is invoked by default. When no
exception is detected & thrown, the control goes to the statement
immediately after the catch block. That is, the catch block is skipped.
This simple try-catch mechanism is illustrated in Program:
Try Block Throwing an Exception
#include<iostream.h>
#include<conio.h>
{
int main()
{
int a,b;
cout << “enter values of a & b \n”;
cin >> a;
cin >> b;
int x = a-b;
try
{
if(x !-0)
{
cout << “Result(a/x) = “ << a/x << “ \n”;
}
else
{
throw(x); // Throws int object
}
}
catch(int i ) // Catches the exception

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
{
cout << “Exception caught : x= “ << x << “\n”;
}
cout << “END”;
return 0;
}
Early & late binding: -
Polymorphism is one of the crucial features of OOP It simply
means one name, multiple forms. Polymorphism concept is
implemented by using the overloaded functions & operators. The
overloaded member functions are selected for invoking by matching
arguments, both type & number. This information is known to the
compiler at the compile time & therefore, complier is able to select the
appropriate function for a particular call at the compile time itself. This
is called early binding or static barding or static linking. Also known as
compile time Polymorphism, early binding simply means that an object
is bound to its function call at compile time.
In runtime polymorphism, an appropriate member function is
selected while the program is running. C+ + supports run time
polymorphism writ the help of virtual functions It is called late or
dynamic binding because the appropriate function is related
dynamically at run time.
When a program is compiled, a sot of binding is don to link all
function calls is e address of functions are put at their calls & similarly
new some calls be resorted at compile time.
Run time e.g. vesture fruition

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
Compile time e.g. friend function or all normal function calls
compile time decisions made by compiler are called early binding
whereas rutime decision making by compiling is called late binding
(run time means when program is sunning or executing).
Operator Overloading Restriction
There are some restrictions that apply to operator overloading: -
1- Operator functions cannot have default arguments.
2- The operators that cannot be overloaded are.
3- One cannot alter the precedence of an operates
4- One cannot change the number of operands that can operator
takes.
General Rules for Overloading Operations
There are certain restrictions & limitations to be kept in mind
while overloading operators they are:
1- Only existing operators can b overloaded. The overloaded
operations must have at least one user-defined operand.
2- It is not recommended to change the basic meaning of an
operator. That is the plus (+) operator should not be
redefined to subtract one value from another. Overloaded
operators follow syntax rules of the original operators.
3- Friend function cannot be used to overload certain operators
like =, (), [] &
4- Unary operators, overloaded by means of a member function
take no explicit argument.
5- Binary operators overloaded through a member function take
one explicit argument & those that are overloaded through a
friend function take two arguments.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
6- Binary operators overloaded through a member function take
no explicit argument.
7- When using binary operations overloaded thorough a member
function, the left hand operand must be an object of the
relevant class.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001
The private qualifies: -
If the “private” qualifier is used when deriving a class, all the
public & protected members of the base class become private member
of the derived class i.e., the members of the base class can be
accessed only within the derived class, they cannot be accessed
through an object of the derived class. The private qualifies is rarely
used. It is used to end a hierarchy of classes.
The protected qualifies: -
The members of a class declared as protected an be accessed
from the derived classes but cannot be accessed from anywhere in
other classes or the main program. In short protected members
behave like public members when it comes to derived classes, &
private members with respect to the rest of the program.
The protected qualifier when used while deriding a class specifies
that all public & protected members of the base class must become
protected members of the derived class. This mans that, like a private
inheritance, these members cannot be accessed through objects of the
derived class, whereas, unlike a private inheritance, they can still be
inherited & accessed by subsequent derived classes, in other words,
protected inheritor does not end a hierarchy of classes, as private
inheritance does.

SCHOOL OF PROGRAMMING
214,Jawahar Marg Sharma 608,Khatiwala Tank Main Road
Complex (Rajmohalla), INDORE Opp. Transport Bank, INDORE
: -3942100 : -2762001

You might also like