c++ with index

65
Index S.No. Contents Page 01. Object Oriented Programming 02 02. What is C++? 05 03. Scope Resolution Operators 07 04. Operator Overloading 09 05. Function in C++ 13 06. Class & Object 19 07. Static Data Member & Member Function 23 08. Array of Object 25 ~ 1 ~

Upload: mukesh-sharma

Post on 24-May-2017

215 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: C++ With Index

Index

S.No. Contents Page

01. Object Oriented Programming 02

02. What is C++? 05

03. Scope Resolution Operators 07

04. Operator Overloading 09

05. Function in C++ 13

06. Class & Object 19

07. Static Data Member & Member Function 23

08. Array of Object 25

09. Constructors & Destructor 27

10. Inheritance 32

~ 1 ~

Page 2: C++ With Index

11. Virtual Base Class 34

12. Virtual Function & Pure Virtual Function 35

13. Polymorphism 38

14. Friend Class and Function 39

15. Templates 43

16. The this Pointer 45

17. Exception Handling 48

18. Bibliography49

Object Oriented Programming

(OOP)

Object Oriented Programming paradigm using object and consisting of data fields and methods together with their interaction to design applications and computer programming. The major motivating factor in the invention of object oriented approach is to remark some of the problem that encountered in the procedural approach. OOP allows decomposition of problem into a no. of entities called object. The organization of data and function in OOP is shown in figure:-

~ 2 ~

Page 3: C++ With Index

Basic concept of OOP:- 1. Object:-

Object is a run time entity with some characteristic and behavior.

OR

An object is a physical entity that exists in real word.

2. Class:-

A class is a logical entity that representing a group of object with common properties and relationship or we can say that a class is a collection of similar types of object. Once classes have been defined then we can create any no. of objects belonging to that class.

3. Inheritance:-

Inheritance is the process by which object of one class acquire the properties of another class. In OOPS the concept of inheritance provides the idea of reusability. This means that we additional features to an existing class without modifying.

4. Polymorphism:-

It is the power of OOP. And it is most important feature of OOP. Polymorphism is a Greek term means the ability to take more than one from. “Polymorphism means one name with multiple tasks”.

~ 3 ~

Page 4: C++ With Index

5. Abstraction:-

Abstraction refers to the act of representing the essential feature without including background details.

6. Encapsulation:-

The wrapping up of data and member function into a single unit (Alt Class) knows an Encapsulation.

Benefits of OOP:-

OOP offers several benefits to both the program designer and the

user. Object Orientation contributes to the solution of many problems associated with the

development with the development and quality of software products. The new technology

promises greater programmer productivity, better quality of software and lesser

maintenance cost. The principal advantages are:

Through inheritance, we can eliminate redundant code and extend the use of existing.

It is possible to have multiple instances of an object to co-exist without any interference.

It is possible to map objects in the problem domain to those in the program.

It is easy to partition the work in a project based on objects.

Object oriented systems can be easily upgraded from small to large system.

~ 4 ~

Page 5: C++ With Index

C++What is C++?

“C++” is an object oriented programming language. It was developed by

“Bjarne Stroustrup”. C ++ is an extension of C with a major addition of the class construct

feature of Simula 67. Since the class was a major addition to the original C language,

Stroustrup initially called the new language ‘C with Classes’. However, later in 1983, the

name was changed to C ++. The idea of C++ comes from the C increment operator ++,

thereby suggesting that C ++ is an augmented version of C.

C++ is a superset of C. Most of what we already know about C applies to C++ also.

Therefore, almost all C programs are also C++ programs. However, there are a few minor

differences that will prevent a C program to run under C++ compiler.

~ 5 ~

Page 6: C++ With Index

The most important facilities that C++ adds on to C are classes, inheritance, function

overloading, and operator overloading. These features enable creating of abstract data

types, inherit properties from existing data types and support polymorphism, there making

C++ a truly object oriented language.

The object-oriented features in C++ allow programmers to build large programs

with clarity, extensibility and ease of maintenance, incorporating the spirit and efficiency of

C. The addition of new features has transformed C form a language that currently

facilitates top - down, structure design, to one that provides bottom up, object oriented design.

Basic Program of C + +# include <iostream.h> / / include header file#include <conio.hint main ( ){

cout << “C++ is better than C. \n”; / / C++ statementreturn 0 ;

}

Applications of C++:- C++ is a versatile language for handling very large programs. It is suitable for virtually any programming task including development of editors, compilers, databases, communication system and any complex real life application system.

Since C++ allows us to create hierarchy - related objects, we can build special object

oriented libraries, which can be used by many programmers.

While C++ is able to map the real world problem properly, the C part of C ++ gives the

language the ability to get close to the machine-level details.

C++ programs are easily maintainable and expandable. When a new feature needs to be

implemented, it is very easy to add to the existing structure of an object.

~ 6 ~

Page 7: C++ With Index

It is expected that C++ will replace C as a general-purpose language in the near future.

For example:-

# include <iostream.h> / / include header file

int main ( )

{float no. 1, no. 2, sum, average;cout <<“enter two numbers” ;cin>>no. 1;cin>>no. 2;sum = no. 1 + no. 2;average = sum/2;cout<<“sum =” <<sum<<“\n”;cout <<“average =” <<average <<“\n”;return 0;

}

Scope resolution operator: - Like C, C++ also a block structured language. Blocks and scope can be used in constructing programs. We know that the same variable name can be used to have different meaning in different blocks. The scope of the variable extends from the points of its declaration till and of the block containing the declaration. A variable declaration inside a block is said to be local to that block.

Consider the following segment of a program: -................................................{

int x =10;..................

}{

int x=1;

~ 7 ~

Page 8: C++ With Index

.........

.........}

The two declaration of x refer to two different memory locations containing different memory locations containing different values. Statement in the second block cannot refer to the variable x declared in the first block, and vice versa.

In C global version of the variable cannot accessed from within the block. C++ resolves this problem introducing new operator (: :) called scope resolution operator.

For example: -

int m=10;void main ( ){ int m=30;

{ int k=m;int m=20;cout << k;

}cout << m;cout << : : m;

}

PROGRAM: SCOPE RESOLUTION OPERATOR

#include<iostream.h>#include<conio.h>int m=10;int main ( ){int m=20;{int k=m;int m=30;cout<<”we are in inner block”;cout<<”k=”<<k<<”\n”;cout<<”: : m=”<<: :m<<”\n”;}cout<<”we are in outer block\n”;cout<<”m=”<<m<<”\n”;

~ 8 ~

Page 9: C++ With Index

cout<<”: :m=”<<: :m<<”\n”;return 0;getch( );}

~ 9 ~

Page 10: C++ With Index

Operator Overloading:- Operator overloading is one of the many exciting features of C+ +. It is an important technique that has enhanced the power of extensibility of C+ +. C+ + tries to make the user defined data types behave in much the same way as the built in types. For eg, C+ + permits us to add two variables of user defined types with the same syntax that is applied to the basic 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 meanings to an operator is known as operator overloading.

Operator overloading provides a flexible option for the creation of new definition for most of C+ + operators. We can almost create a new language of our own by the creative use of the function and operator overloading techniques. We can overload all the C+ + operators except the following.

Class member access operators Scope resolution operator Size operator Condition operator

Defining Operator Overloading:- To define an additional task to an operator we must specify what it means in relation to the class to which the operator is applied. This is done with the help of special function, called operator function, which describes the task. The general form of op. function

return type classname :: operator (op- arg list){

Function body}

Where return type is the type of value returned by the specified operation and op is the operator being overloaded. The op is preceded by the keyword operator. Operator op is the function name.

~ 10 ~

Page 11: C++ With Index

Overloading Unary Operators:- Let us consider the unary minus operator. A minus operator when used as a unary takes just one operand. We know that this operator changes the sign of an operand when applied to a basic data item. We will see here how to overload this operator so that it can be applied to an int or float variable. The unary minus when applied to an object should change the sign of each of its data item.

Program: program shows the unary minus operator is overloaded.

#include<iostream.h>#include<conio.h>class gulshan{private:int x,y,z;public:void get_data(int a,int b,int c); void display(void); void operator-(); //overoaded unary minus operator};void gulshan::get_data(int a,int b,int c){

x=a;y=b;z=c;

}void gulshan::display(void) //Display function of class gulshan{

cout<<x<<" ";cout<<y<<" ";cout<<z<<"\n";

}void gulshan::operator-() //Overloading function{

x=-x;y=-y;z=-z;

}void main(){gulshan g1;g1.get_data(10,-20,30);cout<<"g1 (values) :";g1.display();-g1; //activates operator-() functioncout<<"g1 (values after overloading) :";g1.display();

~ 11 ~

Page 12: C++ With Index

getch();}Output:

g1 (values) :10 -20 30g1 (values after overloading) :-10 20 -30

Overloading Binary Operators:- We have seen how to overload a unary operator. The same mechanism can be used to overload to binary operator. A statement lie

C=sum(A,B);Was used. The functional notation can be replaced by a natural looking expression

C=A+B;By overloading the + operator using an operator + ( ) function.

Program: Program shows the binary plus operator is overloaded.

#include<iostream.h>#include<conio.h>class complex{ float x,y;

public: complex() {} //Default constructorcomplex(float real,float imag){ x=real;

y=imag; }

complex operator+(complex);void display();

}; //………………………………………………………………………………complex complex::operator+(complex c) { complex temp;

temp.x=x+c.x;temp.y=y+c.y;

return(temp); } //……………………………………………………………………………….void complex::display(){ cout<<x<<"+j"<<y<</n; } //………………………………………………………………………………..

~ 12 ~

Page 13: C++ With Index

void main(){ complex c1,c2,c3;

c1=complex(2.5,3.5);c2=complex(1.6,2.7);c3=c1+c2;cout<<"c1 = "; c1.display();cout<<"c2 = "; c2.display();cout<<"c3 = "; c3.display();

getch();}Output :-c1 = 2.5+j3.5c2 = 1.6+j2.7c3 = 4.1+j6.2

The function is expected to add two complex values and return a complex value as the result but receives only one value as argument. Let us look at statement that invokes this function: c3=c1+c2; //invokes operator+( )That member function can be invoked only by object of the same class. Here the object c1 takes the responsibility of invoking the function and c2 plays the role of argument that is passed to the function. The above invocation statement is equal to c3=c1.operator+(c2);In overloading of binary operators, the left hand operand is used to invoke the operator function and the right hand operand is passed as an argument.

~ 13 ~

Page 14: C++ With Index

Functions in C++:- Using functions we can structure our programs in a more modular way, accessing all the potential that structured programming can offer to us in C++.

A function is a group of statements that is executed when it is called from some point of the program. The following is its format:

type name ( parameter1, parameter2, ...) { statements }

where:

type is the data type specifier of the data returned by the function. name is the identifier by which it will be possible to call the function. parameters (as many as needed): Each parameter consists of a

data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

statements is the function's body. It is a block of statements surrounded by braces { }.

Here you have the first function example: // function example#include <iostream>using namespace std;

int addition (int a, int b){ int r; r=a+b; return (r);}

int main (){ int z; z = addition (5,3); cout << "The result is " << z; return 0;}

The result is 8

~ 14 ~

Page 15: C++ With Index

Type of Function:-

1. Function Prototyping:-

The prototype describes the function interface to the

compiler by giving details such as the number and type of augments and the type of return

values. With function prototyping, a template is always used when declaring and defining a

function. When a function is called, the compiler uses the template to ensure that proper

arguments are passed, and the return value is treated correctly. Any violation in matching

the arguments of the return types will be caught by the compiler at the time of compilation

itself.

Function prototyping is a declaration statement in the calling program and if the

following form:-

type function - name (argument - list);

The argument - list contains the types and names of arguments that must be passed

to the function.

We can either include or exclude the variable names in the argument list of

prototypes. The variable names in the prototypes just act as placeholders and, therefore,

if names are used, they don’t have to match the names used in the function call or function

definition.

Call by Reference:- Function call passes arguments by value. The called function creates

a new set of variables and copies the value of arguments into them. The does not have

access to the actual variable in the calling program and can only work copies of value.

In bubble sort we compare two adjacent elements in the list and interchange their

value if the first element in greater than the second element. If a function is used for bubble

sort, then it should be able to alter value of variables in the calling function.Which is not possible if the call by value method is used when we pass the

arguments by call by reference. The formal arguments in the called function become aliases to the ‘actual’ arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data

~ 15 ~

Page 16: C++ With Index

PROGRAM: CALL BY REFERENCE#include<iostream.h>#include<conio.h>class demo{public:void swap (int &x , int &y){x= x+ y;y=x- y;x=x-y;}};void main( ){int a, b;cout<<”enter any two no.=”;cin>> a>>b;demo d;cout<<”values before swap_\n”;cout<<”a =”<<a<<endl;cout<<”b=”<<b<<endl;d . swap ( a , b);cout<<”values after swap_\n”;cout<<”a=”<<a<<endl;cout<<”b=”<<b<<endl;getch( );}

~ 16 ~

Page 17: C++ With Index

2. Inline function:-

One of the objectives of using functions in a program is to save

some memory space, which becomes appreciable when a function is likely to be called many

times. However, every time a function is called, it takes a lot of extra time in executing a

series of instructions for takes such as jumping to the function, saving registers, pushing

arguments into the stack, and returning to the calling function. When a function is small, a

substantial percentage of execution time may be spent in such overheads.

C++ has a different solution to this problem. To eliminate the cost 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 follow:-

inline function - header

{

function body

}

For example:-

inline double cube (double a)

{

return (a*a*a);

}

~ 17 ~

Page 18: C++ With Index

Program to Inline function:-# include < iostream.h># include <conio.h>inline int add (int x, int y){

return ( x+y);}inline float sub (float a, float b){

return (a - b);}int main ( ){

clrscr ( );int p = 12;int q = 20;cout << “the result of the program”;cout << add(p,q);float m = 12 .6;float n = 2 .65;cout << “the result of the program”;cout << sub (m,n);getch ( );

}

~ 18 ~

Page 19: C++ With Index

Function overloading: -

Overloading refers to the use the same thing for different

purposes. C++ also permits overloading of functions. This means that we can use the same

function name to create functions that perform a variety of different tasks. This is known as

function polymorphism in OOP.

Using the of function overloading we can design a family of function with one

function name but with different argument lists. The function would perform different

operation depending on the argument list in the function call. The correct function to be

invoked is determined by checking the number and function type.

Program to Function Overloading

#include<iostream.h>#include<conio.h>int add (int ,int );float add (float ,float );void main ( ){int x=10 , y= 20 ,z;float a = 10.5, b =10.9 , c ;z= add (x , y);c = add (a , b);cout<<”Sum of integer=”<<z;cout<<”Sum of float=”<<c;getch( );}int add (int x, int y){return(x+y);}float add (float a , float b){return(a +b );}

~ 19 ~

Page 20: C++ With Index

CLASS & OBJECT

Class:-

One of the major features of C++ is classes. They provide a method of binding

together data and functions which operate on them. Like structure in C, classes are user

defined data types. We just mentioned that objects contain data, and code to manipulate

that data. The entire set of data and code of an object can be made a user defined data type

with the help of a class.

In fact, objects are variable of the type class. Once a class has been defined, we can

create any number of objects belonging to that class. Each object is associated with the data

of type class with which they are created. A class is thus a collection of similar type. Classes

are user defined data types and behave like the built-in types of a programming language.

The syntax used to create an object is no different than the syntax used to create an integer

object in C.

The syntax:-

class <class name>{ private

public....................

};void main ( ){ ..........

..........}

~ 20 ~

Page 21: C++ With Index

Program to using the class:-# include <iostream.h># include <conio.h>class person{

char name [30];int age ;

public :void getdata (void);void display(void);

};void person : : getdata (void){

cout <<“enter name:”;cin>> name;cout<<“enter age:”;cin>>age;

}void person : :display (void){

cout <<“\n Name:” <<name ;cout <<“\n Age:” <<age ;

}int main ( ){

person p;clrscr ( );p. getdata( );p. display( );return (0);getch( );

}

~ 21 ~

Page 22: C++ With Index

Generally a Class specification has two parts:-

1. Class declaration

2. Class function definition

Class declaration describes the type and scope of its members. The class function

describes how the class functions are implemented.

The class declaration is similar to a struct declaration. The keyword class specifies

that what follows is an abstract data of type class name. The body of a class is enclosed

within braces and terminated by a semicolon. These functions and variables are

collectively called class members. The keywords private and public are known as visibility

labels. Note that these keywords are followed by a colon.

Defining a member function:-

1. Outside the class definition

2. Inside the class function

1. Outside the class definition:- Member functions that are declared inside a class

have to be defined separately outside the class. Their definitions are very much like the

normal functions. They should have a function header and a function body. Since C++ does

not support the old version of function definition, the ANSI prototype form must be used for

defining the function header.

For example:-

class person{ char name [30];

int age ;public :void getdata (void);

};void person : : getdata (void){ cout <<“enter name:”;

cin>> name;cout <<name;}

2. Inside the class definition:-

~ 22 ~

Page 23: C++ With Index

Another method of defining a member function is to

replace the function declaration by the actual function definition inside the class. Foe

example, we could define the item class as follows:

For example:-

Class item

{

int number;

float cost;

public :

void getdata (int a, float b);

void putdata (viod);

{

cout << number ;

cout << cost;

}

};

~ 23 ~

Page 24: C++ With Index

Static Data Member and Member Function

Static Data Member:- A data member of a class can be qualified as static. The

properties of a static member variable are similar to that of a C static variable. A static member variable has certain special characteristics. These are:

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

initialization is permitted.

Only one copy of that member is created for the entire class and is shared by

by all the objects of that class, no matter how many objects are created.

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.

For example, a static data member can be used as a counter that records the occurrences of

all the objects.

Program to Static Data Member:-

# include <iostream .h># include <conio.h>class item{ int number;

int count;public : voidgetdata (int a){ number = a;

count++;}public : void disp( ){ cout<<count;}

};void main ( ){ clrscr( );

item i1,i2,i3;i1. getdata (100);i2. getdata (200);i3. getdata (300);i1. disp ( );i2. disp ( );i3. disp ( );getch ( );

}

~ 24 ~

Page 25: C++ With Index

Static Member Function:- Like, static member variable we can also have static

member functions. That is declared static has the following properties:-

1. A static function can have access to only other static members (function, variable)

declared in the same class.

2. A static member function can be called using class name instead of it’s an object as

follow:-

class - name : : function - name;

Program to static member function:-# include < iostream.h># include <conio.h>class test { int code;

static int count;public : void set_code ( void){ code = ++count;}public : void show_count ( void){ cout<<“object number” << code;}public : static void show_count ( void){ cout<<“count ” << count;}};

int test : : count;int main ( ){ test t1,t2,t3;

t1.set_code( );t2.set_code( );test : : show_count( );t3.set_code( );test : : show_count( );t1.show code( );t2.show code( );t3.show code( );getch( );

}

~ 25 ~

Page 26: C++ With Index

Array of Object:- An array can be of any data types including structure. Similarly we

can also have arrays of variable that are of the type Class. Such variables are called arrays of

objects.

An array of objects is stored inside the memory in the same way as a multi-

dimensional array. The array manager is represented. Note that only the space for data

items of the objects is created. Member functions are stored separately and will be used by

all the objects.

For examples:-

class employee

{

char name [30];

float age;

public :

void getdata (void);

void putdata (void);

};

PROGRAM: ARRAY OF OBJECTS

~ 26 ~

Page 27: C++ With Index

#include<iostream.h>#include<conio.h>class employee{ char name[30];int age;public:void get_data( );void display ( );};void employee: :get_data( ){ cout<<”enter name=”; cin>>name; cout<<”enter age=”; cin>>age;}void employee : : display ( ){ cout<<”name=”<<name<<endl; cout<<”age=”<<age<<endl;}void main( ){ employee emp; for(int i =0;i<=5;i++){cout<<”enter details of employee”<<i+1<<endl;emp[i] . get_data( );}for(int i =0 ;i< = 5;i++){ cout<<”details of employee”<<i+1<<”is”<<endl; emp [ i ] .display ( ); }getch( );}

~ 27 ~

Page 28: C++ With Index

Constructors & DestructorConstructors:- A constructor is a ‘special’ member function whose task is to initialize the

objects of its class. It is special its name is the same as the class name. The constructor is

invoked whenever an object of its associated class is created. It is called constructor because

it constructs the values of data members of the class.

It is a member function which can automatically call when objects are created. Constructors

are used to initialization of the objects.

The constructor functions have some special characteristics. These are:-

1. They should be declared in the public section.

2. They are invoked automatically when the objects are created.

3. They do not have return types, not even void therefore, and they cannot

return values.

4. We cannot refer to their addresses.

5. They cannot be inherited, through a derived class can call the base class constructor.

6. Like other C++ functions, they can have default arguments.

7. Constructor cannot be virtual.

8. An object with a constructor cannot be used as a member of a union.

PROGRAM: CONSTRUCTOR#include<iostream.h>#include<conio.h>class product{int a, b,c ;public:product ( ){ a=0;b=0;}product( int x ,int y ){a = x;b = y;}void calculate ( ){c = a * b ;}void display ( ){cout<<”Product=”<<c;}};void main( ){Product p;P . calculate ( );P . display ( );getch( );}

~ 28 ~

Page 29: C++ With Index

Parameterized Constructors:-

The constructor initializes the data members of the

entire object to zero. It may be necessary to initialize the various data elements of the

different objects with different values when they are created. C++ permits us to achieve this

objective by passing arguments to the constructors. Functions when the objects are created

the constructors that can take arguments are called “parameterize Constructors”.

The constructor integer ( ) may be modified to take arguments shown as:-

class integer

{

int m, n;

public :

integer (int x, int y); // parameterized constructor

.............. ;

.............. ;

};

integer : : intger ( int x, int y)

{

m = x;

n = y;

}Dynamic initialization of Constructors:-

C++ permits initialization of the variable at a

run time. This is referred to as Dynamic initialization. Class objects can be initialized

dynamically too. That is to say, the initial value of an object may be providing during run

time. One advantage of Dynamic initialization is that we can provide various initialization

formats, using overloaded constructors. This provides the flexibility of using different format

as data at run time depending upon the situation.

~ 29 ~

Page 30: C++ With Index

For example: -int main ( )

{

int

cout <<“enter two numbers” ;

cin>>no. 1;

cin>>no. 2;

int sum = no. 1 + no. 2;

int average = sum/2;

cout<<“sum =” <<sum<<“\n”;

cout <<“average =” <<average <<“\n”;

return 0;

}

Copy Constructors: -

It takes a reference to an object of same class as itself as an

argument. A copy constructor is used to declare and initialized an object from an object. The

process of initializing through a copy constructor is known as copy initialization. A reference

variable has been used as an argument by the copy constructors. We cannot pass the

argument by value to the copy constructor.

~ 30 ~

Page 31: C++ With Index

Destructor:- Destructor is a member function, which can be automatically called when

objects are created. Destructor is used to destroy the memory that has been created by a

construct.

Destructor is declared in public sector. It may not take any argument and does not

return any value. Only one destructor is sufficient to destroy the memory that has been

created by more than one constructor.

A destructor never takes any argument nor does it return any value. It will be

invoked implicitly by the compiler upon exit from the program to clean up storage that is no

longer accessible. It is a good practice to declare destructors in a program since it releases

memory space for future use.

Whenever new is used to allocate memory in the constructors, we should use

delete to free that memory.

For example: -

matrix : : ~ matrix ( )

{

for (int i-0; i<=3; i++)

delete p[i];

delete p;

}

~ 31 ~

Page 32: C++ With Index

PROGRAM: DESTRUCTOR#include<iostream.h>#include<conio.h>class aaddition{int a, b , c;public:addition( ){count ++;cout<<”object”<<count<<”created”;}~addition( ){cout<<”object”<<count<<”destroyed”;count--;}void get_data1( ){cout<<”enter first no=”;cin>>a;}void get_data2( ){cout<<”enter second no.=”;cin>>b;}void calculate(addition &x ,addition &y){c=x.a+y.b;}void display( addition &z ){cout<<”sum=”<<z.c;}};void main(){addotion d1 ,d2;d1 .get_data1( );d2 .get_data2( );addition d3;d3 .calculate(d1 ,d2);addition d4;d4 .display( );d4 . display(d3);getch();}

~ 32 ~

Page 33: C++ With Index

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.

Inheritance provides the idea of 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 classes.

The real appeal and answer and power of the inheritance mechanism is that it allows the

programmer to reuse a class that is almost, but not exactly, what he wants, and to tailor the

class in such a way that it not introduce any undesirable side-effects into the rest of the

classes.

For Example: -

The bird ‘robin’ is a part of the class ‘flying bird’, which is again a part of the class ‘bird’. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as illustrated.

PROGRAM:SINGLE INHERITANCE

~ 33 ~

Page 34: C++ With Index

#include<iostream.h>#include<conio.h>class base{ int a;protected:int b;public:int c;void get data();int get_a( ); };class child : private base{public:void sum( );void display( ); };void base: :get data( ){ cout<<”enter any two no.=”;cin>>a>>b; }int base : : get_a( ){ return( a);}void child: :sum(){ get data( );c=b+get_a( ); }void child : :display( ){cout<<”sum of”<<get_a( )<<”and”<<b<<”=”<<c; }void main( ){ child ch;ch.sum( );ch.display( );getch( );}

~ 34 ~

Page 35: C++ With Index

Virtual base classes:- Suppose you have two derived classes B and C that have a common base class A, and you also have another class D that inherits from B and C. You can declare the base class A as virtual to ensure that B and C share the same subobject of A.

In the following example, an object of class D has two distinct subobjects of class L, one through class B1 and another through class B2. You can use the keyword virtual in front of the base class specifiers in the base lists of classes B1 and B2 to indicate that only one subobject of type L, shared by class B1 and class B2, exists.

For example:

class L { /* ... */ }; // indirect base classclass B1 : virtual public L { /* ... */ };class B2 : virtual public L { /* ... */ };class D : public B1, public B2 { /* ... */ }; // valid

Using the keyword virtual in this example ensures that an object of class D inherits only one subobject of class L.

A derived class can have both virtual and nonvirtual base classes. For example:

class V { /* ... */ };class B1 : virtual public V { /* ... */ };class B2 : virtual public V { /* ... */ };class B3 : public V { /* ... */ };class X : public B1, public B2, public B3 { /* ... */};

In the above example, class X has two subobjects of class V, one that is shared by classes B1 and B2 and one through class B3.

~ 35 ~

Page 36: C++ With Index

Virtual Function & Pure Virtual Function

Virtual Function:- Virtual means existing in a fact but not in reality. Virtual function is

one that does not really exist but never less appears real to some parts of the program. The

need of the virtual function is that suppose we have a number of different classes but we

want to put them all on a list and perform a particular operation on them using the function

call. When we use the same function name in both the base and derived classes, the

function in base class is declared as virtual using the keyword virtual preceding its normal

declaration. When a function is made virtual C++ determines which function to use at run

time based on the type of object pointed to by the base pointer, the than the type of

pointer. Thus, by making the base pointer to print to different objects, we can execute

different versions of the virtual function.

Rules of Virtual function:-

1. The Virtual functions must be members of some class.

2. They cannot be static members.

3. They are accessed by using object pointers.

4. A Virtual function can be a friend of another class.

5. A Virtual function in a base class must be defined, even though it may not be

used.

6. We cannot have Virtual constructors, but we can have virtual destructors.

For Example:-

class base

{

public :

void display ( )

{cout << “display base”;}

virtual void show ( )

{cout << “show base”;}

};

PROGRAM:VIRTUAL FUNCTION

~ 36 ~

Page 37: C++ With Index

#include<iostream.h>#include<conio.h>class demo{public:void display( ){ cout<<”display function of base class”;}virtual void show( ){cout<<”show function of base class”;} };class child:public demo{ public:void display( ) { cout<<”display function of child class “;}void show( ){ cout<<”show function of child class”;} }void main( ){ demo *p;child ch;p=&ch;p->display( );p->show( );demo d;p=&d;p->display( );p->show( );getch( );}

~ 37 ~

Page 38: C++ With Index

Pure Virtual Function:- A Pure Virtual function is a Virtual function with no body.

There is a common situation where no need for the base class version of the particular

function in derived classes. When this true, the body of Virtual function in the base class can

be removed and the notation equal to zero. We have not defined any object of class media

and therefore the function display ( ) in the base class has been defined ‘empty’. Such

functions are called ‘do nothing’ function.

A do nothing function may be defined

Virtual void display ( ) = 0;

Such functions are called pure virtual function.

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 requires each derived class to either

define the function or re declare it as a pure virtual function. A class containing pure virtual

function cannot be used to declare any objects of its own. Such are called abstract base

classes. The main objective of an abstract class is to provide some traits to the derived

classes and to create a base pointer required for achieving run time polymorphism.

For example :-

class base

{ public : virtual void show ( )= 0;

};

class derive : public base

{ public : void show ( )

{ cout <<“function in derive :” ;

}

};

~ 38 ~

Page 39: C++ With Index

Polymorphism:-

Polymorphism is another important OOP Concept. Polymorphism, a

Greek words, Poly means ‘many’ and morphism means ‘behavior’. An operation may exhibit

different behaviors in different instances. The behavior depends upon the types of data

used in the operation.

Polymorphism plays an important role in allowing objects having different internal

structure to share the same external interface. This means that a general class of operation

may be accessed in the same manner even though specific actions associated with each

operation may differ. Polymorphism is extensively used in implementing inheritance.

For example: -

The operation of addition for two numbers, the operation will generate a

sum. If the operands were string, then the operation would produce a third string by

concatenation. The process of making an operator to exhibit different behaviors in different

instances is known as operator overloading.

~ 39 ~

Page 40: C++ With Index

Friend Class and Function

Friend functions In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends.

Friends are functions or classes declared with the friend keyword.

If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend:

// friend functions#include <iostream>using namespace std;

class CRectangle { int width, height; public: void set_values (int, int); int area () {return (width * height);} friend CRectangle duplicate (CRectangle);};

void CRectangle::set_values (int a, int b) { width = a; height = b;}

CRectangle duplicate (CRectangle rectparam){ CRectangle rectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres);}

int main () { CRectangle rect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << rectb.area(); return 0;}

24

~ 40 ~

Page 41: C++ With Index

The duplicate function is a friend of CRectangle. From within that function we have been able to access the members width and height of different objects of type CRectangle, which are private members. Notice that neither in the declaration of duplicate() nor in its later use in main() have we considered duplicate a member of class CRectangle. It isn't! It simply has access to its private and protected members without being a member.

The friend functions can serve, for example, to conduct operations between two different classes. Generally, the use of friend functions is out of an object-oriented programming methodology, so whenever possible it is better to use members of the same class to perform operations with them. Such as in the previous example, it would have been shorter to integrate duplicate() within the class CRectangle.

~ 41 ~

Page 42: C++ With Index

Friend classes:- Just as we have the possibility to define a friend function, we can also define a class as friend of another one, granting that first class access to the protected and private members of the second one.

// friend class#include <iostream>using namespace std;

class CSquare;

class CRectangle { int width, height; public: int area () {return (width * height);} void convert (CSquare a);};

class CSquare { private: int side; public: void set_side (int a) {side=a;} friend class CRectangle;};

void CRectangle::convert (CSquare a) { width = a.side; height = a.side;} int main () { CSquare sqr; CRectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0;}

16

In this example, we have declared CRectangle as a friend of CSquare so that CRectangle member functions could have access to the protected and private members of CSquare, more concretely to CSquare::side, which describes the side width of the square.

You may also see something new at the beginning of the program: an empty declaration of

~ 42 ~

Page 43: C++ With Index

class CSquare. This is necessary because within the declaration of CRectangle we refer to CSquare (as a parameter in convert()). The definition of CSquare is included later, so if we did not include a previous empty declaration for CSquare this class would not be visible from within the definition of CRectangle.

Consider that friendships are not corresponded if we do not explicitly specify so. In our example, CRectangle is considered as a friend class by CSquare, but CRectangle does not consider CSquare to be a friend, so CRectangle can access the protected and private members of CSquare but not the reverse way. Of course, we could have declared also CSquare as friend of CRectangle if we wanted to.

Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.

~ 43 ~

Page 44: C++ With Index

Templates:- Template is one of the features added to C++ recently. It is a new

concept which enables us to define generic classes and functions and thus provides support

for generic programming. Generic programming is an approach where generic types are

used as parameters in algorithm so that they work for a variety of suitable data types and

data structures.

A template can be used to create a family of classes of functions. For example, a

class template for an array class for an array class would enable us to create arrays of

various data types such as int array and float array. Similarly, we can define a template a

template for a function, say mul ( ), that would help us create various versions of mul ( ) for

multiplying int, float and double type values.

A template can be considered as a kind of macro. A template is defined with a

parameter that would be replaced by a specified data type at the time of actual use of the

class or function; the templates are sometimes called “parameterized classes or function.

As mentioned earlier, templates allow us to define generic classes. It is a simple

process to create a generic class using a template with an anonymous type. The general

format of a class template is:-

template <class T>

class Class name

{

/ / .........

/ / class member specification

/ / with anonymous type T

/ / wherever appropriate

/ / .........}

~ 44 ~

Page 45: C++ With Index

PROGRAM:CLASS TEMPLATE

#include<iostream.h>#include<conio.h>Template <class t>class demo{ T sum;T *a;public:demo(){ a=newt[5];}demo(T * x){ for(int i=0;i<5;i++){ a[i]=x[i]; }void calculate(){ sum=0;for(int i=0;i<5;i++){ sum=sum=a[i]; }void display(){ cout<<”sum=”<<sum<<endl;} };void main(){ int x[5]={1,2,3,4,5};float y[5]={1.1,1.2,1.3,1.4,1.5};demo <int>d1(x);demo <float>d2(y);d1.calculate();d2.calculate();d1.display();d2.dispaly();getch();}

~ 45 ~

Page 46: C++ With Index

The this pointer :-

The keyword this identifies a special type of pointer. Suppose that you create an object named x of class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it.

A static member function does not have a this pointer.

The type of the this pointer for a member function of a class type X, is X* const. If the member function is declared with the const qualifier, the type of the this pointer for that member function for class X, is const X* const.

A const this pointer can by used only with const member functions. Data members of the class will be constant within that function. The function is still able to change the value, but requires a const_cast to do so:

void foo::p() const{ member = 1; // illegal const_cast <int&> (member) = 1; // a bad practice but legal }

A better technique would be to declare member mutable.

If the member function is declared with the volatile qualifier, the type of the this pointer for that member function for class X is volatile X* const. For example, the compiler will not allow the following:

struct A { int a; int f() const { return a++; }};

The compiler will not allow the statement a++ in the body of function f(). In the function f(), the this pointer is of type A* const. The function f() is trying to modify part of the object to which this points.

The this pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions.

For example, you can refer to the particular class object that a member function is called for by using the this pointer in the body of the member function. The following code example produces the output a = 5:

#include <iostream>using namespace std;

struct X {private: int a;public: void Set_a(int a) {

~ 46 ~

Page 47: C++ With Index

// The 'this' pointer is used to retrieve 'xobj.a' // hidden by the automatic variable 'a' this->a = a; } void Print_a() { cout << "a = " << a << endl; }};

int main() { X xobj; int a = 5; xobj.Set_a(a); xobj.Print_a();}

In the member function Set_a(), the statement this->a = a uses the this pointer to retrieve xobj.a hidden by the automatic variable a.

Unless a class member name is hidden, using the class member name is equivalent to using the class member name with the this pointer and the class member access operator (->).

The example in the first column of the following table shows code that uses class members without the this pointer. The code in the second column uses the variable THIS to simulate the first column's hidden use of the this pointer:

Code without using this pointer

Equivalent code, the THIS variable simulating the hidden use of the this pointer

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

struct X {private: int len; char *ptr;public: int GetLen() { return len; } char * GetPtr() { return ptr; } X& Set(char *); X& Cat(char *); X& Copy(X&); void Print();};

X& X::Set(char *pc) { len = strlen(pc); ptr = new char[len]; strcpy(ptr, pc); return *this;}

X& X::Cat(char *pc) {

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

struct X {private: int len; char *ptr;public: int GetLen (X* const THIS) { return THIS->len; } char * GetPtr (X* const THIS) { return THIS->ptr; } X& Set(X* const, char *); X& Cat(X* const, char *); X& Copy(X* const, X&); void Print(X* const);};

X& X::Set(X* const THIS, char *pc) { THIS->len = strlen(pc); THIS->ptr = new char[THIS->len]; strcpy(THIS->ptr, pc); return *THIS;}

X& X::Cat(X* const THIS, char *pc) {

~ 47 ~

Page 48: C++ With Index

Code without using this pointer

Equivalent code, the THIS variable simulating the hidden use of the this pointer

len += strlen(pc); strcat(ptr,pc); return *this;}

X& X::Copy(X& x) { Set(x.GetPtr()); return *this;}

void X::Print() { cout << ptr << endl;}

int main() { X xobj1; xobj1.Set("abcd") .Cat("efgh");

xobj1.Print(); X xobj2; xobj2.Copy(xobj1) .Cat("ijkl");

xobj2.Print();}

THIS->len += strlen(pc); strcat(THIS->ptr, pc); return *THIS;}

X& X::Copy(X* const THIS, X& x) { THIS->Set(THIS, x.GetPtr(&x)); return *THIS;}

void X::Print(X* const THIS) { cout << THIS->ptr << endl;}

int main() { X xobj1; xobj1.Set(&xobj1 , "abcd") .Cat(&xobj1 , "efgh");

xobj1.Print(&xobj1); X xobj2; xobj2.Copy(&xobj2 , xobj1) .Cat(&xobj2 , "ijkl");

xobj2.Print(&xobj2);}

Both examples produce the following output:

abcdefghabcdefghijkl

~ 48 ~

Page 49: C++ With Index

Exception Handling:-

Exception handling is a mechanism that separates code that detects and handles exceptional circumstances from the rest of your program. Note that an exceptional circumstance is not necessarily an error.

When a function detects an exceptional situation, you represent this with an object. This object is called an exception object. In order to deal with the exceptional situation you throw the exception. This passes control, as well as the exception, to a designated block of code in a direct or indirect caller of the function that threw the exception. This block of code is called a handler. In a handler, you specify the types of exceptions that it may process. The C++ run time, together with the generated code, will pass control to the first appropriate handler that is able to process the exception thrown. When this happens, an exception is caught. A handler may re throw an exception so it can be caught by another handler.

PROGRAM: EXCEPTION HANDLING

#include<iostream.h>#include<conio.h>int main( ){int a,b;cout<<”enter values of a and b\n”;cin>>a>>b;int x=a-b;try{if(x!=0){cout<<”result(a/xx)=”<<a/x<<”\n”;}else{throw(x);}}catch(int i){cout<<”exception caught;x=”<<x<<”\n”;}cout<<”end”;return o;getch();}

~ 49 ~

Page 50: C++ With Index

BIBLIOGRAPHY

1: ‘C++’

By G.S. Baluja

2: ‘C++ Object Oriented Programming’

By Lipchutz

~ 50 ~