Top Banner
0.0 C++ (or) Cpp C++ is a extension of c-language because we use ++ after c that is c++. =>It is developed by BJrane stroustrup in early 1980’s (or) In some books it is preferred as 1983. =>C++ is said to be objective oriented programming language (OOPL) because in it we work with streams known as objects.
215
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: c++

0.0 C++ (or) Cpp

C++ is a extension of c-language because we use +

+ after c that is c++.

=>It is developed by BJrane stroustrup in early

1980’s (or) In some books it is preferred as 1983.

=>C++ is said to be objective oriented programming

language (OOPL) because in it we work with streams

known as objects.

=>We know that ‘c’ is structured programming language

or (pop – procedure oriented programming language) but

C++ is oops based system

=>In ‘c’ programming can be done with the help of

functions

In c++ it can be done with the help of objects known as

streams. These are two types

Page 2: c++

1) Input stream

2) Output stream

In ‘c’ when we doing a program we can

include the header file =>stdio.h

While as in c++ we can include =>iostream.h

=>In ‘c’ regularly printf(); and scanf(); functions are used

for Input and Output operations

Where as in c++ we use Cin & Cout objects (streams) as

input & output operators

=>In C++ we are write in main() as void main() which

returns no values.

New features of C++:-

Some of the no of c++ programs are listed below.

Key words used in c++ other than ‘c’:-

Page 3: c++

To support object oriented program in system c++

introduces new key word in addition to that of ‘c’.

The following are the list of new key words used in c++.

As friend private this static cast catch inline protected

through dynamic cast class new public virtual overload

delete operators template try type-id.

Reference variables:-

C++ introduces a new kind of variable known as reference

variable with provide an alternative name for provide

defined variable.

For example the variable sum is a reference to the variable

total than sum and total can be used.

Inter change able to represent that variable is given below.

A reference can be created by using the following general

format.

Page 4: c++

Data type & reference-name=variable-name

Ex:-

int total=100;

int & sum=total;

In the above example ing type variable that has been

already declared.

Sum is the alternative name declared to represent the

variable total.

So both of the variables refer to the same data object in the

memory of the statements

Cout<<total;

Cout<<sum; both print the value 100

Operator in c++:-

Page 5: c++

C++ has a each set to operators all c-operator are valued in

c++ also . In addition c++ introduces same new operator

are listed below.

Operator Meaning

:: => Scope resolution operator

::* => Pointer-to-member declaratory

->* => Pointer-to-member operator.

.* => Pointer-to-member operator

delete => Memory release operator

endl => Line feed operator

new => Memory allocation operator.

Type cast operator =>Explicit type conversion of

variables

Page 6: c++

(or) expression.

Scope resolution operator:-

C++ is a block structured language. Blocks and scopes can

be used in containing programs. The scope of the variable

extended from the point of its declaration end the block

declaration.

Default arguments:-

In a c++ function call one or more arguments are emitted

the function may take default for emitted arguments by

providing default values in the proto type. In arguments

are specified the compiled when they not specified by the

programmer explicitly.

Type cost operator:-

C++ for means exploiter type of conversions of expression

using the type cost operators.

Page 7: c++

The following are two versions which are

(type – name) expression => c-notation

Type – name (expression) => c++-notation

Ex:-

avg=sum/(float)i; =>c-notation

avg=sum/float(i); =>c++-notation

type-namebehaves as if it is a function to

convert the values to a designated type. It can

be used only if the type is an identifier.

Operator over loading:-

Over loading means assigning different

meanings to an operation depending on the

context.

Page 8: c++

C++ for means over loading of operators,

allowing to assign multiple meanings to

operators.

1) The operators used for operator

overloading are scope resolution:-

(::) operators.

2) Conditional operators:- (?;)

3) Size of operator (size of int,float)

Basic data type c++:-

Data type:-The kind of data that variable in

programming language is called as a data type

C++ offers a set of data types they

can be classified into three types is

given below.

Page 9: c++

1) User defined data type

2) Built – in data type

3) Derive data type

OOPS:-

OOPS stands for – “object oriented

programming system” and which is supported

by c++.

This oops concept introduces some new

concepts which are listed below.

1) Classes and objects

2) Data abstraction and encapsulation

3) Inheritance

4) Polymorphism

5) Dynamic binding

Page 10: c++

6) Message passing

OOPS can be classified into two types

1) OBPL => (object based

programming language)

2) OOPL => (object oriented

programming language)

OBPL:-

Supports all the features of oops except

inheritance, dynamic binding, and message

passing.

OOPL:-

Supports OBPL features of oops except

inheritance, dynamic binding message passing.

Benefits of object oriented programming system:-

Page 11: c++

The following are the benefits of object oriented

programming to the user and the program designing

1) The principle of data hide in help the

programmer to

Build the secure programs .It is easy to partition the

work in a project based on objects.

2) object oriented system can be easily up

graded from small to large system. We can

eliminate the redundant code and entered

the use of existing classes

3) OOP provide an advantage in production

and maintenance of software.

4) Object Oriented Program involves the

identification and implementation of

different classes of objects and their

behavior

Page 12: c++

5) Software complexity can be easily

managed .

6) It is possible to have multiple instances of

an object to co-exist without any

interference.

7) OOP leads to saving of development time

and higher productivity.

Applications of object oriented program:-

OOPS are extensively used in the

development of most software systems.

Today oop is used in the design of graphic

user interfaces on systems such as

windows.

The following are the different areas for

application of oop.

1) Artificial intelligence and expert system

2) Simulation and model series studies

Page 13: c++

3) Object oriented database systems

4) Real time systems

5) Object oriented operating system

6) Multimedia applications

7) Graphical user interfaces (GUI)

8) Computer based training and education

systems

Input and Output stream:-

A stream is a flow of data which is also known as

object. These are categorized into two types

1)Input stream

2)Output stream

Which are located in the header file iostream.h

Which is must used in our program whenever the

program is writing in the c++ editor

Input stream:-

Page 14: c++

The stream which is used to input the data is known as

input stream. In c++ ‘c’ in object is used as input

stream and which is connected to the standard input.

Cin is used to read a number a character or a string of

characters from a standard input device.

It uses an extraction operator “>>” with Cin object. The

general format for Cin input stream is as follows.

Cin>>variable name;

Ex:-

Cin>>a;

If single Cin object is used with more than one input

variable then this type of operation is said to be “cascading

input operation”

Cin>>variable 1>>variable 2>>---------- >>variable n;

Ex:- Cin>>m1>>m2>>m3;

Page 15: c++

Output stream:-

The stream which is used to display the data as output is said

to be output stream.

In c++ Cout object is used as output stream and which is

connected to the standard output. Cout is used to display an

object on to the standard output device.

The insertion operator “<<” is used with Cout object . The

general format of Cout output stream is as follows.

Cout<<variable name;

Ex:-

Cout<<a;

If single Cout object is used with more than one output

variable then this type of operation is said to be

“cascading output operation”

Page 16: c++

Cout<<variable 1<<variable 2<< ---------- <<variable n;

Ex:- Cout<<m1<<m2<<m3;

Opening c++ editor:-

i) start -> run -> command -> ok -> cd\ ->enter -> cd

tcc -> enter -> tc -> Alt+enter(full screen)

ii) start -> run -> c:\tcc\tc: exe -> enter->ok

1) Write a c++ program to swap two variables without

using third variable?

#include<iostream.h>

#include<conio.h>

void main()

{

int a,b;

clrscr();

cout<<”enter a and b values:”;

Page 17: c++

cin>>a>>b;

a+=b;

b=a-b;

a-=b;

cout<<”after swapping: a=”<<a<<”\t b=”<<b;

getch();

}

Output:-

Enter a and b values:8 9

After swapping: a=9 b=8

***********************************

2) Write a c++ program to print biggest of two

numbers?

#include<iostream.h>

#include<conio.h>

void main()

{

Page 18: c++

int a,b;

clrscr();

cout<<”enter a and b values:”;

cin>>a>>b;

if(a>b)

cout<<”a=”<<a<<” is big”;

else

cout<<”b=”<<b<<” is big”;

getch();

}

Output:-

Enter a and b values:8 9

b=9 is big

********************************

3) Write a c++ program to find the given number is

prime (or) not?

#include<iostream.h>

Page 19: c++

#include<conio.h>

void main()

{

int n,i,count=0;

clrscr();

cout<<”enter number:”;

cin>>n;

i=1;

cout<<”factors:”;

while(i<=n)

{

if(n%i—0)

{

cout<<i<<”\t”;

count++;

}

i++;

Page 20: c++

}

if(count==2)

cout<<n<<”is prime”;

else

cout<<n<<” is not prime”;

getch();

}

Output:-

1) enter number:7

factors:1 7 7 is prime

2) enter number:8

factors: 1 2 4 8 8is not prime

**************************************

4) Write a c++ program to print big & small array

elements?

#include<iostream.h>

#include<conio.h>

Page 21: c++

void main()

{

int i,r,a[10],big,small;

clrscr();

cout<<”enter range:”;

cin>>r;

cout<<”enter “<<r<<” elements into array:”;

for(i=0;i<r;i++)

cin>>a[i];

cout<<”the “<<r<<” array elements are:\n”;

for(i=0;i<r;i++)

cout<<a[i]<<”\t”;

big=a[0];

small=a[0];

for(i=0;i<r;i++)

{

if(big<a[i])

Page 22: c++

big=a[i];

else if(small>a[i])

small=a[i];

}

cout<<”big=”<<big<<”small=”<<small;

getch();

}

Output:-

Enter range:6

Enter 6 elements into array:7 8 9 5 4 3

The 6 array elements are:

7 8 9 5 4 3 big=9 small=3

**********************************

Structure of c++ program:-

Include files

Class declaration

Member function definition

Page 23: c++

Main() program

Object creation for the class

Access specifies of a c++ program:-

Access specifies are used to tell the access of data in the

current working program. These are classified into three

types.

1) Private

2) Public

3) Protected

Private:-

With this access specifies the private numbers of a class

are inaccessible outside the class.

Private:-

All data numbers and functions declared in the public

section of the class can be accessed any where in the

Page 24: c++

program that means either inside the class or outside the

class also.

Protected:-

Classes and objects:-

A class is syntactically similar to a structure in c. Classes

and objects are the main ideas of the object oriented

programming tools . In ‘c’ the structure contains one or

more variables (data items) called members of a structure

are grouped together as a single unit.

In c++, a class is similar to a structure data type but it

contains not only data element but also functions which

operates on data elements.

Class definition:-

A class is a way to bind the data members and member

functions into a single unit.

It allows the data to be hidden if necessary from external

use.

Page 25: c++

When defining a class we are creating a new abstract data

type that can be treated like any other built in data type.

The class declaration describes the type and scope of its

numbers.

The functions and variables used in a class are

called members of a class

The variables declared inside the class are known

as

“data members” and the functions are known as “member

functions”.

Method of creating objects:-

In c++ object is a variable of class type (or) it is known as an

instance of class. Objects are basic run time entities in an

object oriented program.

General format of class declaration:-

Class <class name>

Page 26: c++

{

Private:

Data members declaration;

Member function definition;

Public:

Data members declaration;

Member function definition;

};

General format of object creation:-

Class name <object name>;

Page 27: c++

Class name obj1,obj2,-------objn;

From the above general format class is a keyword and it is

abstract data type of class name. The body of class is

enclosed with in braces and terminated by ;.

The body of class contains declaration of variable and

functions. These are grouped under two sections namely

private and public.

“By default the members are private”

In the general format of object creation class name is a name

of he user defined class and obj1,obj2,-------objn are user

defined objects.

Class student

{

Int sno,m1,m2,m3,tot;

Float avg; Accessing private members inside the class only

Char sname[10]; Class creation.

Public:

Page 28: c++

Void getdata();

Void putdata();

};

Void main()

{ Accessing public members outside the class only

student s; Object creation

s.getdata();

s.putdata();

}

Accessing class members:-

Accessing of class members are of two types namely

1) Accessing data members

2) Accessing members functions.

Accessing data members:-

Once an object of a class has been created they must be a

provision to access this members. This is achieved by using

the member access operator. ‘.’

Page 29: c++

The syntax of accessing data members of a class is given

below.

Object name. data member

Ex:-s.rno

In the above general format object name is the name of the

user defined object and data member is the member which is

declared inside the class.

Accessing member functions:-

The data member of a class must be declared with in the body

of the class. Where as the member functions of the class can

be defined in any of the following ways.

1) Inside the class specification

2) Outside the class specification

Member functions inside the class specification:-

Page 30: c++

The syntax for specifying member function declaration is

similar to a normal function definition except that is enclosed

with in the body of a class all the member functions defined

with in the body of the class are treated as inline by default

except those members having looping statements such as

(while, do while, for loop).

Member function outside the class specification:-

This can be done by using scope resolution operator the

general syntax is as shown below.

Return type class name :: member function name(arg list)

{

Body of the function;

}

Page 31: c++

A class name is the user defined class name. Here scope

resolution operator acts as an identity – label to inform the

compiler, the class to which the function belongs.

5) Write a c++ program to demonstrate class and object

concept find swapping of two numbers without using third

variable?

#include<iostream.h>

#include<conio.h>

Class swap

{

int a,b;

public:

void getdata()

{

cout<<”enter a and b values:”;

cin>>a>>b;

}

Page 32: c++

void swapnum()

{

a+=b;

b=a-b;

a-=b;

}

void putdata()

{

cout<<”after swapping: a=” <<a<< ”\t b=”<<b;

}

};

void main()

{

clrscr();

swap s;

s.getdata();

s.swapnum();

Page 33: c++

s.putdata();

getch();

}

Output:-

Enter a and b values:78 90

After swapping: a=90 b=78

*****************************************

6) Write a c++ program find the biggest of two

numbers?

#include<iostream.h>

#include<conio.h>

Class big

{

Public:

Void getdata()

{

Cout<<”enter a and b values:”;

Page 34: c++

Cin>>a>>b;

7) Write a c++ program to find sum of digits of a

given number?

#include<iostream.h>

#include<conio.h>

class sum

{

int n,sum,r;

public:

void getdata();

void sum_of_digits();

void putdata();

};

void sum::getdata()

{

cout<<”enter number:”;

cin>>n;

Page 35: c++

}

void sum::sum_of_digits()

{

sum=0;

while(n>0)

{

r=n%10;

sum+=+r;

n/=10;

}

}

void sum::putdata()

{

cout<<”sum of digits of a given number is=”<<sum;

}

void main(){

clrscr();

Page 36: c++

sum s;

s.getdata();

s.sum_of_digits();

s.putdata();

getch();

}

Output:-

Enter number:678

Sum_of_digits of a given number is:21

*****************************************

8) Write a c++ program to find factorial of a given

number?

#include<iostream.h>

#include<conio.h>

Class fact

{

Page 37: c++

9) Write a c++ program to find reverse of a given

number?

#include<iostream.h>

#include<conio.h>

class num

{

int n,r,sum;

public:

void getdata();

void reverse();

void putdata();

};

void num::getdata()

{

cout<<”enter number:”;

cin>>n;

}

Page 38: c++

void num::reverse()

{

sum=0;

while(n!=0)

{

r=n%10;

sum=sum*10+r;

n/=10;

}

}

void num::putdata()

{

cout<<”reverse of a given number “<<sum<<” is reverse”;

}

void main()

{

clrscr();

Page 39: c++

num s;

s.getdata();

s.reverse();

s.putdata();

getch();

}

Output:-

Enter number:567

Reverse of a given number 765 is reverse.

*************************************

Constructors and destructors:-

Constructors:-Constructors is a special member function

which is used to initialize the variables.

The name of the constructor is like a class name or same as

class name.

Page 40: c++

Its task is put initialize the object of its class that is

constructor is invoked. Whenever an object of its associated

class is created.

It is called a constructor because with construct the value of

data members of the class.

There is no need to call the constructor explicitly like any

other member function.

Constructor characteristics:-

A constructor function have some special characteristics are

as follows.

=> Constructors declared in public section of a class only.

=> These are invoked automatically. When the objects are

created.

=> Constructor do not have return value (or) return types.

=> A constructor can not be virtual.

=> Constructor cannot be inherited (this function cannot

generalize the properties of other function (or) class)

Page 41: c++

Types of constructor:-

Constructors are categorized into four types. They are

1) default constructor

2) parameterized constructor

3) copy constructor

4) dynamic constructor

Default constructor:-

A default constructor function initialize the data member of a

class and it is having no arguments (or) parameters with it. It

is also known as parameter less constructor.

The general syntax of default constructor is as follows.

Page 42: c++

Class class name

{

Public:

Class name()

{ Default constructor

(Initialization of data members of a class) Ex:-

} a=0

}; b=50,c=35

To call the constructor are to invoke it from outside the class.

We follow the below general format.

Class name :: class name()

{

Statements;

Page 43: c++

}

10) Write a c++ program to demonstrate default

constructor concept to print given variable values

and find reminder?

#include<iostream.h>

#include<conio.h>

class def

{

int a,b;

public:

def ()

{

a=b=0;

}

void getdata()

{

cout<<”enter a and b values:”;

Page 44: c++

cin>>a>>b;

}

void modnum()

{

cout<<”reminder of “<<a<<” and “<<b<<” is: “<<a%b;

}

};

void main()

{

clrscr();

def d;

d.getdata();

d.modnum();

getch();

}

Output:-

Enter a and b values:9 4

Page 45: c++

Reminder of 9 and 4 is:1

*************************************

Parameterized constructor:-

C++ permits arguments to a constructor with arguments is

known as parameterized constructor (or) constructor with

arguments it accepts parameters or arguments. When the

object is created that is we pass the values with object

creation.

The general format for parameterized constructor is as

follows.

Class name (argument list or parameter list)

{

Statements;

}

11) Write a c++ program to demonstrate

parameterized constructor concept to find area of

rectangle?

Page 46: c++

#include<iostream.h>

#include<conio.h>

class area

{

int l,b;

public:

area();

area(int,int);

void rectarea();

};

area::area()

{

l=b=0;

}

area::area(int l1,int b1)

{

l=l1;

Page 47: c++

b=b1;

}

void area::rectarea()

{

cout<<”area of rectangle having length “<<l<<” and breadth

“<<b<<” is: “<<l*b<<endl;

}

void main()

{

clrscr();

area a,a1(5,3);

a.rectarea();

a1.rectarea();

getch();

}

Page 48: c++

Output:-

Area of rectangle having length 0 and breadth 0 is:0

Area of rectangle having length 5 and breadth 3 is:15

*************************************

12) Write a c++ program to find square root and

power of its given numbers?

#include<iostream.h>

#include<conio.h>

#include<math.h>

class sqrtpow

{

int n,x;

public:

sqrtpow();

sqrtpow(int,int);

void sqrtnum();

void pownum();

Page 49: c++

};

sqrtpow::sqrtpow()

{

n=x=0;

}

sqrtpow::sqrtpow(int n1,int x1)

{

n=n1;

x=x1;

}

void sqrtpow::sqrtnum()

{

cout<<n;

float s=sqrt(n);

cout<< “sqrt of “<<n<<” is:”<<s<<endl;

}

void sqrtpow::pownum()

Page 50: c++

{

int p=pow(x,n);

cout<<x<<”power of “<<n<<” is:”<<p;

}

void main()

{

clrscr();

sqrtpow s,s1(5,3);

s1.sqrtnum();

s1.pownum();

getch();

}

Output:-

5 sqrt of 5 is:2.236068

3 power of 5 is:243

*******************************

Copy constructor:-

Page 51: c++

Copy constructor is always used when the compiler has to

create a temporary object of class object

(or)

The copy constructor is used when the initialization of one

object by another and object of the same class. These are used

in the following situations.

The initialization of object by another object of

the same class

Return of a object as a function value

Starting the object as by value parameter of a

function.

The syntax of copy constructor is as follows.

Class name::class name(class name & object name)

{

Statements;

}

Page 52: c++

13) Write a c++ program to demonstrate copy

constructor concept to copy(or) to assign one

object properties?

#include<iostream.h>

#include<conio.h>

class abc

{

int a,b,c;

public:

abc();

abc(int,int,int);

abc(abc &,int);

void putdata();

};

abc::abc()

{

a=b=c=0;

Page 53: c++

}

abc::abc(int x,int y,int z)

{

a=x;

b=y;

c=z;

}

abc::abc(abc &s,int p)

{

a=s.a;

b=s.b;

c=p;

}

void abc::putdata()

{

cout<<”a “<<a<<”b “<<b<<”c “<<c<<endl;

}

Page 54: c++

void main()

{

clrcsr();

abc a1,a2(4,5,9),a3(a2,7);

a1.putdata();

a2.putdata();

a3.putdata();

getch();

}

Output:-

A0b0c0

A4b5c9

A4b5c7

*************************************

Dynamic constructor:-

The constructor can also used to allocate memory, while

creating objects. This will enable the system to allocate the

Page 55: c++

right amount of memory for each object. When the object are

not of the same size.

Allocation of memory to objects at the time of their

constructions is known as dynamic construction of objects.

In dynamic construction the memory is allocated by using

new operator.

14) write a c++ program to demonstrate dynamic

constructor concept?

#include<iostream.h>

#include<conio.h>

#include<string.h>

class c1

{

char *str;

Page 56: c++

public:

c1()

{

strcpy(str,” “);

}

c1(char *s)

{

int l=strlen(s);

s=new char[l+1];

strcpy(str,s);

}

void getdata()

{

cout<<”enter string:”;

cin>>str;

}

void putdata()

Page 57: c++

{

cout<<str;

}

};

void main()

{

clrscr();

c1 b1,b2(“aptech”),b3;

b1.putdata();

b2.putdata();

b3.getdata();

b3.putdata();

}

Ouvvtput:-

Destructors:-

A destructor function is automatically invoked when an

object is destroyed.

Page 58: c++

The primary usage of destructor function is to release the

space on the keep.

A destructor function may be invoked explicitly.

The following are syntax rules for creating a destructor

fuinction.

A destructor function name is same as that of class. Except

that first character of the name must be ~ (tilde character)

A destructor have public access in class declaration.

=> The destructor function takes no arguments.

=> It cannot return any value

=> It cannot be declared in static, constant or volatile.

=> It takes no arguments that is it cannot be over loaded.

The general syntax of destructor function is

~class name()

{

Statements;

Page 59: c++

}

15) Write a c++ program to demonstrate destructor

function functions?

16) Write a c++ program to destroy the objects of a

class by using destructor concept?

#include<iostream.h>

#include<conio.h>

class c1

{

int a,b;

public:

c1()

{

a=b=0;

}

c1(int x,int y)

{

Page 60: c++

a=x;b=y;

}

~c1()

{

cout<<”destroying the objects of a class” <<endl;

}

void putdata()

{

cout<<”a” <<a<< “b” <<b<<endl;

}

};

void main()

{

clrscr();

c1 a,a1(10,20);

a.putdata();

a1.putdata();

Page 61: c++

}

Output:-

a0b0

a10b20

destroying the objects of a class

destroying the objects of a class

FUNCTIONS

Definition:-

Function is a self contained programming segment. To

perform specific and well defined task.

Functions are classified into four types. They are listed below.

1) Function without arguments without return

values.

2) Function with arguments without return value.

3) Function with arguments with return value

4) Function without arguments with return value.

17)Function without arguments without return values:-

Page 62: c++

#include<iostream.h>

#include<conio.h>

class c1

{

int a,b;

public:

void getdata()

{

cout<< “enter a and b values:”;

cin>>a>>b;

void putdata()

{

cout<<”the addition is:”<<a+b;

}

};

void main()

{

Page 63: c++

clrscr();

c1 s;

s.getdata();

s1.putdata();

getch();

}

Output:-

Enter a and b values:8 6

The addition is:14

***************************************

18) Function with arguments without return value :-

#include<iostream.h>

#include<conio.h>

class c1

{

int a,b;

public:

Page 64: c++

void mul(int a1,int a2)

{

a=a1;

b=a2;

}

void putdata()

{

cout<<”the multiplication is: “<<a*b;

}

};

void main()

{

clrscr();

c1 s;

s.mul(5,6);

s.putdata();

getch();

Page 65: c++

}

Output:-

The multiplication is:30

**************************************

19) Write a c++ program to find a given number is

prime or not?

#include<iostream.h>

#include<conio.h>

Class c1

{

Int n,I,count;

Public:

Int prime(int n1)

{

N=n1;

I=1;

Count=0;

Page 66: c++

While(i<=n)

{

If(n%i==0)

{

Cout<<i<<”\t”;

Count++;

}

I++;

}

If(count==2)

Return n;

}

};

Void main()

{

Int p;

Clrscr();

Page 67: c++

C1 s;

P=s.prime(37);

Cout<<”prime=”<<p;

Getch();

}

Output:-

1 37 prime=37

*************************************

Function with arguments with return value:-

20) Write a c++ program to print factorial of a given

range?

#include<iostream.h>

#include<conio.h>

class c1

{

int i,f;

public:

Page 68: c++

int factorial(int n1)

{

i=1;f=1;

while(i<=n1)

{

f=f*i;

i++;

}

return f;

}

};

void main()

{

clrscr();

c1 s;

fact=s.factorial(5)

cout<<”factorial=” <<fact;

Page 69: c++

getch();

}

Output:-

Factorial=120

***********************************

21) Write a c++ program with argument with return

to find the given number is perfect or not?

Function without arguments with return values:-

22) Write a c++ program to find the reminder by

using without arguments with return values?

#include<iostream.h>

#include<conio.h>

class abc

{

public:

int modnum();

};

Page 70: c++

int abc::modnum()

{

int a,b;

cout<<”enter a and b values:”;

cin>>a>>b;

return a%b;

}

void main()

{

int p;

clrscr();

abc a;

p=a.modnum();

cout<<”reminder=:<<p;

getch();

}

Output:-

Page 71: c++

Enter a and b values:78 12

Reminder=6

***************************************

Function with default arguments:-

One of the most useful facilities available in c++ is the

facility to define default argument values are given.

Whenever a call is made to a function without specifying an

argument, the program will automatically assign values to the

parameters from the default function proto type declaration .

At the time of calling the function we can omit the arguments

from right or we can omit all the arguments.

We cannot omit the arguments from left or middle.

23) Write a c++ program to demonstrate function

with default arguments concept?

#include<iostream.h>

#include<conio.h>

Page 72: c++

class abc

{

public:

void mul(int=1,int=2,int=3);

};

void abc::mul(int a,int b,int c)

{

cout<<”product of “<<a<<” “<<b<<” and “<<c<<” is

“<<a*b*c<<endl;

}

void main()

{

clrscr();

abc a;

a.mul();

a.mul(12);

a.mul(12,10);

Page 73: c++

a.mul(12,10,15);

getch();

}

Output:-

Product of 1 2 and 3 is 6

Product of 12 2 and 3 is 72

Product of 12 10 and 3 is 360

Product of 12 10 and 15 is 1800

***********************************

Over loading:-

In c++ the member function that can be changed in two forms

namely.

Compile time and run time forms.

The first form of the member function is again of

the two types they are

1) Function overloading

Page 74: c++

2) Operator over loading

The second form of the member function that can

be changed at run time is called virtual function

that is represented as following.

polymorphism

Page 75: c++

compile time Run time

Function Operator virtual

over loading over loading function

Over loading is a language feature that allows “the function

(or) operator to be given more than one definition”.

The type of arguments with the function or operator is called

over loading.

The member function that can be changed at run time is

called virtual function.

Function over loading:-

Page 76: c++

The function over loading is a logical method of calling of

several functions with different arguments and data types that

perform identical things by the same thing

(or)

Giving same name to different function with perform

different task is called function over loading (or) functional

polymorphism. The function over loading allows to use same

function name for various data types.

The function declaration, definition and calling of these

functions are done with the same function but they differ in

number of arguments or type of arguments (or) return type

(or) all.

Advantages of function over loading:-

1) Eliminating the use of different function names

for the same operation.

2) Function over loading has easy maintainability of

code.

Page 77: c++

3) Better understanding of the relation between

program and outside overloading

4) Function over loading helps to understand and

debug easily.

24) write a c++ program to demonstrate function over

loading concept to add two integers, two float and

double?

#include<iostream.h>

#include<conio.h>

class funload

{

public:

int add(int,int);

float add(float,float);

double add(double,double);

};

int funload::add(int x,int y)

Page 78: c++

{

return x+y;

}

float funload::add(float x,float y)

{

return x+y;

}

double funload::add(double x,double y)

{

return x+y;

}

void main()

{

clrscr();

funload f;

int a,b,a1;

float x,y,a2;

Page 79: c++

double p,q,a3;

cout<”enter two integer values:”;

cin>>a>>b;

a1=f,add(a,b);

cout<<”enter two float values:”;

cin>>x>>y;

a2=f,add(x,y);

cout<<”enter two double values:”;

cin>>p>>q;

a3=f.add(p,q);

cout<<”addition of two integer values “<<a<<” and “<<b<<”

is “<<a1;

cout<<”addition of two float values “<<x<<” and “<<y<<” is

“<<a2;

cout<< “addition of two double values “<<p<<” and “<<q<<”

is “<<a3;

getch();

Page 80: c++

}

Output:-

Enter two integer values:34 67

Enter two float values:45 56

Enter two double values:23 37

Addition of two integer values 34 and 67 is 101

Addition of two float values 45 and 56 is 101

Addition of two double values 23 and 37 is 60

**************************************

25) Write a c++ program to find volumes of cube,

cuboids, and cylinder?

#include<iostream.h>

#include<conio.h>

#define pi 3.14

class volume

{

public:

Page 81: c++

int vol(int);

int vol(int,int,int);

double vol(double,double);

};

int volume::vol(int s)

{

return s*s*s;

}

int volume::vol(int l,int b,int h)

{

return l*b*h;

}

double volume::vol(double r,double h)

{

retyrn pi*r*r*h;

}

void main()

Page 82: c++

{

clrscr();

volume v;

int v1=v.vol(5);

int v2=v.vol(3,4.3);

double v3=v.vol(5.362,4.325);

cout<<” volume of cube= “<<v1<<endl;

cout<<” volume of cuboids= “<<v2<<endl;

cout<<” volume of cylinder= “<<v3;

getch();

}

Output:-

Volume of cube=125

Volume of cuboids=121

Volume of cylinder=390.453553

*************************************

Operator over loading:-

Page 83: c++

Operator over loading is one of the special feature of c++.

The operators +, -, +=,-=, >>, << etc. are

designed to operate on standard data types only in

structured programming like ‘c’.

The operator + is used to perform the addition

operation on integers, floating point (or) mixed

data types as indicated in the mixed expression

a+b.

Int a, b, c;

Float x, y, z;

C=a+b; => addition of two integers and integer assignment

Z=x+y; => addition of two float values and floating point

assignment

X=a+b; => addition of two integers and floating point

assignment.

Here the operators +,= behave differently in above statements.

Page 84: c++

It indicates that the operator + is overloaded implicitly to

operator on operance of user defined data types.

Definition:-

Able to associate a number function along with an operator to

work on objects of a class is called operator over loading (or)

operational polymorphism.

This cannot change the basic usage of operators.

The operator over loading provides the additional

meaning to the operators. Such as +, *, +=, >=

etc.

When they applied to user defined data types.

In this operator over loading also the precedence

of operators is same.

We can write the function as normal member function or as

friend function.

Polymorphism:-

Page 85: c++

The word polymorphism derived from the greek words poly

and morphism.

Poly means many and morphism means action to be

performed that is performing many actions on single operator.

c++ provides a void verity of operators to

perform the operation on various operands.

The operators are classified into the following types.

Sno Operator category Operators

1 Arithmetic operators +, -, *, /, %

2 Logical operators &&, ||, !

3 Comparison operators >, <, >=, <=, !=, ==

4 Multiple assignment +=, -=, *=, /=

Operators

5 Unary operators ++, --

6 Input and output operators <<, >>

Page 86: c++

c++ provides a flexible options for the creation of

new definition for the most of c++ operators.

The following of the operators which are not used

for operator overloading.

Sno Operator category Operators

1 Class member operators .2 Scope resolution operators ::

3 Size operators size of

4 Conditional operators ?:

5 Direct pointer number .*

6 preprocessor symbols #, ##

Declaration of operator over loading:-

The general form of operator over loading is

Page 87: c++

Return type operator operator symbol(arglist or parameters)

{

Body of operator function;

}

A return type is the function return type

Operator is keyword

Operator symbol is the operator to be over loaded

Parameters are the arguments to the operator

function

Ex:-

1) Void sum ++();

2) Int sum +(int x,int y);

3) Rules for operator over loading

The following are the rules for over loading of operators.

Page 88: c++

1) Only those operators that are predefined in the c+

+ compiler can be used and users cannot allowed

to create new operators.

2) Over loading an operator never gives a meaning

which is radically different from its natural

meaning.

3) Using operators over load at by means of a

member function take no explicit arguments and

return no explicit values.

4) The over loaded operator must have at last one

operant that is of user defined type.

5) We cannot use friend functions to over load

creation operators

6) The overloaded operators follows the syntax rules

of original operators.

7) The binary arithmetic operators such as +, -, *, /

must explicitly return a value.

Page 89: c++

8) They not attempt to change their one arguments.

26) Write a c++ program ++ and – operators over

loading?

#include<iostream.h>

#include<conio.h>

#include<string.h>

class c1

{

char *str;

public:

c1();

c1(char *);

void putdata();

void operator ++();

void operator –();

};

c1::c1()

Page 90: c++

{

strcpy(str,” “);

}

c1::c1(char *p)

{

int l=strlen(p);

str=new char[l+1];

strcpy(str,p);

}

void c1::putdata()

{

cout<<str<<endl;

}

void c1::operator ++()

{

cout<<strupr(str)<<endl;

}

Page 91: c++

void c1::operator --()

{

cout<<strlwr(str)<<endl;

void main()

{

clrscr();

c1 o,o1(“aptech”),o2(“program”);

o1.putdata();

o2.putdata();

++o1;

--o2;

getch();

}

Output:-

aptech

PROGRAM

APTECH

Page 92: c++

program

*************************************

27) > operator over loading:-

#include<iostream.h>

#include<conio.h>

#include<string.h>

class c1

{

char *str;

public:

void getdata();

int operator>(c1);

};

void c1::getdata()

{

cout<<”enter string:”;

cin>>str;

Page 93: c++

}

int c1::operator>(c1 ob)

{

return strcmp(str,ob.str);

}

void main()

{

clrscr();

c1 o1,o2;

o1.getdata();

o2.getdata();

int x=o1>o2;

if(x==0)

cout<<”equal”;

else if(x>0)

cout<<”first one is greater”;

else if(x<0)

Page 94: c++

cout<<”second one is greater”;

getch();

}

Output:-

Enter string:kalyani

Enter string:sudha

Second one is greater

***************************************

28) Binary operator + over loading:-

Returning objects:-

#include<iostream.h>

#include<conio.h>

class student

{

int tel, hin, eng;

public:

void getdata();

Page 95: c++

void putdata();

student operator + (student);

};

void student::getdata()

{

cin>>tel>>hin>>eng;

}

void student::putdata()

{

cout<<tel<<” “<<hin<<” “<<eng<<endl;

}

student student::operator + (student ob)

{

student a;

a.tel=tel+ob.tel;

a.hin=hin+ob.hin;

a.eng=eng+ob.eng;

Page 96: c++

return a;

}

void main()

{

clrscr();

student t1,t2,res;

cout<<”enter first test marks:”;

t1.getdata();

cout<<”enter second test marks:”;

t2.getdata();

cout<<”the first test marks:”<<endl;

t1.putdata();

cout<<”the second test marks:”<<endl;

t2.putdata();

res=t1+t2;

cout<<”resultant marks:”<<endl;

res.putdata();

Page 97: c++

getch();

}

Output:-

Enter first test marks:23

24

21

Enter second test marks:23

20

19

The first test marks:

23 24 21

The second test marks:

23 20 19

Resultant marks:

46 44 40

***********************************

29) Compound assignment operator over loading:-

Page 98: c++

Returning addresses:-

#include<iostream.h>

#include<conio.h>

#include<string.h>

const size=50;

class string

{

char str[size];

public:

string();

string (char *);

void putdata();

string & operator += (string &);

};

string::string()

{

strcpy(str,” “);

Page 99: c++

}

string::string(char *s)

{

strcpy(str,s);

}

void string::putdata()

{

cout<<”string”<<endl;

cout<<str;

}

string & string::operator += (string &x)

{

if(strlen(str)+strlen(x.str)<size)

{

strcat(str,x.str);

return (*this);

}

Page 100: c++

else

{

cout<<”the string is too long”;

return (*this);

}

}

void main()

{

clrscr();

string st,st1(“learn”),st2(“computer”),st3(“at home”);

st1+= st2+= st3;

st1.putdata();

getch();

}

Output:-

String

Learn computer at home

Page 101: c++

&&&&&&&&&&&&&&&&&&&&&&&&&

30) = operator over loading:-

#include<iostream.h>

#include<conio.h>

#include<string.h>

class string

{

char *str;

public:

string();

string(char *);

void putdata();

string & operator=(string &);

};

string::string()

{

strcpy(str,” “);

Page 102: c++

}

string::string(char *s)

{

strcpy(str,s);

}

string & string::operator=(string &x)

{

delete str;

strcpy(str,x.str);

return(*this);

}

void string::putdata()

{

cout<<str<<endl;

}

void main()

{

Page 103: c++

string st,st1(“aptech”);

st=st1;

st.putdata();

getch();

}

Output:-

APTECH

***********************************

FRIEND FUNCTIONS:-

Friend functions are the functions an access private

data of the classes are it is friend.

Friend functions can be declared in private are public sections

of the class.

Friend functions are the defined as any other normal

functions.

To declared a functions as a friend place “friend” key word.

Page 104: c++

To call the friend functions there is no need to use the object

of any class.

Syntax:-

friend return type function name (argument list)

{

body of function;

}

31) write a c++ program to demonstrate friend function

concept?

#include<iostream.h>

#include<conio.h>

class c2;

class c1

Page 105: c++

{

int a;

public:

void getdata();

friend void add (c1,c2);

};

class c2

{

int b;

public:

void getdata();

friend void add (c1,c2);

};

void c1::getdata()

{

cout<<”enter a value (c1 data)”;

cin>a;

Page 106: c++

}

void c2::getdata()

{

cout<<”enter b value (c2 data)”;

cin>>b;

}

void add (c1 o1,c2 o2)

{

cout<<”addition of

“<<o1.a<<”and”<<o2.b<<”is”<<o1.a+o2.b;

}

void main()

{

clrscr();

c1 aa;

c2 bb;

aa.getdata();

Page 107: c++

bb.getdata();

add (aa,bb);

getch();

}

Output:-

enter a value (c1 data) 67

enter b value (c2 data) 56

addition of 67 and 56 is 123

*************************************

32) Write a c++ program to find biggest of two numbers

using friend function concept?

#include<iostream.h>

#include<comio.h>

class c1;

class c1

{

int a;

Page 108: c++

public:

void getdata();

friend void biggest (c1,c2);

};

class c2

{

int b;

public:

void getdata();

friend void biggest (c1,c2)

};

void c1::getdata()

{

cout<<”enter a value (c1 data)”;

cin>>a;

}

void c2::getdata()

Page 109: c++

{

cout<<”enter b values (c2 data)”;

cin>>b;

}

void biggest (c1 01,c2 o2)

{

if(01.a>o2.b)

cout<<”a is big a=”<<o1.a<<endl;

else

cout<<”b is big b=”<<o2.b;

}

void main()

{

clrscr();

c1 aa;

c2 bb;

aa.getdata();

Page 110: c++

bb.getdata();

biggest (aa,bb);

getch();

}

Output:-

Enter a value (c1 data) 56

Enter b value (c2 data) 89

B is big = 89

FRIEND CLASSES:-

33) Write a c++ program to demonstrate Friend class concept

to find reverse of a given number?

#include<iostream.h>

#include<conio.h>

class c2;

class c1

{

int n;

Page 111: c++

public:

void getdata();

friend class c2;

};

class c2

{

public:

void reverse (c1);

};

void c1::getdata()

{

cout<<”enter a number:”;

cin>>n;

}

void c2::reverse (c1 o)

{

int r;

Page 112: c++

while (o.n>0)

{

r=o.n%10;

cout<<r;

o.n/=10;

}

}

void main()

{

clrscr();

c1 aa;

c2 bb;

aa.getdata();

bb.reverse (aa);

getch();

}

output:-

Page 113: c++

enter a number:5678

8765

************************************

34) Write a c++ program to find given number is perfect (or)

not?

STATIC DATA MEMBERS:-

In a class the members declared as static are called static data

members.

Static members means they will be initialized the only once

no matter how many objects are created.

We should define static data members of a class before main()

Type class name :: variable name;

Page 114: c++

35) Write a c++ program to demonstrate static data member

concept?

#include<iostream.h>

#include<conio.h>

class c1

{

static int a;

public:

c1()

{

a++;

}

~c1()

{

a--;

}

void putdata()

Page 115: c++

{

cout<<”a value is=”<<a<<endl;

}

};

int c1::a;

void main()

{

clrscr();

c1 aa;

aa.putdata();

c1 bb;

bb.putdata();

c1 cc;

cc.putdata();

c1 dd;

dd.putdata();

getch();

Page 116: c++

}

Output:-

a value is = 1

a value is = 2

a value is = 3

a value is =4

************************************

STATIC MEMBER FUNCTIONS:-

Static member functions are used to manipulate on static data.

Static member functions are called by class name,

with scope resolution operator.

It is not possible to call static member functions.

By using object of a class. General format for

static member function is as follows.

Static return type function name()

{

Page 117: c++

Statements;

}

A static member function does not have a this

pointer . So it can access non-static members of

its class only by using ‘.’ Or =>.

The static member function cannot be a virtual

function.

36) Write a c++ program to demonstrate static member

concept?

#include<iostream.h>

#include<conio.h>

class c1

{

static int a;

public:

static void putdata()

Page 118: c++

{

a++;

cout<<”a value is=”<<a<<endl;

}

};

int c1::a;

void main()

{

clrscr();

c1::putdata();

c1::putdata();

c1::putdata();

c1::putdata();

getch();

}

output:-

a value is = 1

Page 119: c++

a value is = 2

a value is = 3

a value is = 4

***************************************

CHARACTERISTICS OF STATIC DATA MEMBERS:-

Static data member is initialized to zero. When first object of

its class is created only one member is created for the entire

class and shared by all objects of the class. Static data

member is visible only with in the class but its life time is the

entire program.

Array of objects:-

An array is a user defined data type have in array of variables

of type class. Such a variables (objects) are called array of

objects.

Page 120: c++

37) Write a c++ program to demonstrate array of object

concept calculated students total & average by accepting their

names & rno with student marks?

#include<iostream.h>

#include<conio.h>

class student

{

int rno,m1,m2,m3,tot;

char name[10];

float avg;

public:

void getdata();

void cal();

void putdata();

};

void student::getdata()

{

Page 121: c++

cout<<”enter rno name m1 m2 m3:”;

cin>>rno>>name>>m1>>m2>>m3;

}

void student::cal()

{

tot=m1+m2+m3;

avg=tot/3;}

void student::putdata()

{

cout<<”rno”<<” “<<”name”<<” “<<”m1”<<” “<<”m2”<<”

“<<”m3”<<” “<<”total”<<” “<<”avg”<<endl;

cout<<rno<<” “<<name<<” “<<m1<<” “<<m2<<”

“<<m3<< “ “<<tot<<” “<<avg<<endl;

}

void main()

{

clrscr();

Page 122: c++

student s[10];

int i,r;

cout<<”enter range:”;

cin>>r;

for(i=0;i<r;i++)

s[i].getdata();

for(i=0;i<r;i++)

s[i].cal();

for(i=0;i<r;i++)

s[i].putdata();

getch();

}

output:-

enter range: 2

enter rno name m1 m2 m3 :

3 ert 34 56 45

enter rno name m1 m2 m3 :

Page 123: c++

4 des 35 46 67

rno name m1 m2 m3 total avg

3 ert 34 56 45 135 45

rno name m1 m2 m3 total avg

4 des 35 46 67 148 49

**************************************

THIS POINTER:-

The keyword THIS is a pointer variable which

always contains the address of the object.

THIS pointer is implicitly defined in each

member function because it is of the special type

of pointer.

The member function has every object that access

to a pointer named THIS which points to the

object itself.

Page 124: c++

Using THIS pointer any member function can

find out the address of the object which it is a

member.

THIS pointer can also be used to access the data

in the object.

Suppose that you create an object named as z of class c1 and

class c1 has non static member function that is fun(). If you

want the function by using z.fun(). The keyword THIS in the

body of the function store the address of (z) (object) or holds

the address of variable.

A static member function does not have THIS

pointer. It takes only non- static members.

THIS pointer is passed as an hidden argument to

all non-static member function call and available

as local variable with in the body of all non-static

functions.

Page 125: c++

Method of accessing member of a class from with in a class

using THIS pointer is as follows.

class test

{

int a;

public:

fun1()

{

statements;

}

fun2()

{

THIS -> a; => Refers to a data member

THIS -> fun1(); => refers to a member function

}

};

Page 126: c++

38) Write a c++ program to access a variable or data member

of a class by using THIS pointer?

#include<iostream.h>

#include<conio.h>

class c1

{

int a;

public:

void assign(int a1)

{

this -> a=a1;

}

void print()

{

cout<<”value of a=”<<a;

}

};

Page 127: c++

void main()

{

clrscr();

c1 c;

int s=5;

c.assign(s);

c.print();

getch();

}

Output:-

Value of a = 5

***************************************

INLINE FUNCTION:-

Every time a function is called it takes a lot of extre time in

executing a series of instructions for tasks such as jumping to

the function save registers etc.

Page 128: c++

“function execution involves the over head of jumping to and

from the calling statements”.

This causes the execution time is consider only large.

Whenever a function is small. In such cases inline function is

used.

The syntax of inline function is as follows.

Inline return type <function name> (argument list)

{

Body of functions

}

The size of object code is considerably reduced

The inline function make a program run fast. That is it

increases the execution speed.

39) Write a c++ program to demonstrate inline function

concept?

Page 129: c++

#include<iostream.h>

#include<conio.h>

inline int add(int x,int y)

{

return x+y;

}

inline float sub(float x,float y)

{

return x-y;

}

void main()

{

int a,b;

float p,q;

clrscr();

cout<<”enter a and b values:”;

cin>>a>>b;

Page 130: c++

cout<<”enter p and q values:”;

cin>>p>>q;

cout<<”addition of two integers=”<<add(a,b)<<endl;

cout<<”subtraction of two float values=”<<sub(p,q);

getch();

}

output:-

enter a and b values: 4 8

enter p and q values: 7 6

addition of two integers = 12

subtraction of two float values = 1

**************************************

FUNCTION TEMPLATES:-

When a single function is written for a family of similar

functions is called as the function template.

The general format of function template is

Page 131: c++

Template <class t>

Return type function name (arguments of type T)

{

Body of the function;

}

The function template syntax is similar to that of class

template. Except that defining the functions instead of classes.

Advantages of function templates:-

The main advantages of function template is

avoid in unnecessary repetition the source code.

In function template full data checking is carried

out the function template does not specify the

actual data types of the arguments.

40) Write a c++ program to demonstrate function template

concept to swap different data type values?

#include<iostream.h>

Page 132: c++

#include<conio.h>

Template <class T>

Void swap(Ta,Tb)

{

T temp;

temp=a;

a=b;

b=temp;

cout<<”a value is:”<<a<<” “<<”b value is:”<<b<<endl;

}

void main()

{

clrscr();

swap(3,9);

swap(4.3,6.9);

swap(“abcd”,”defg”);

swap(4.36987129,4.32158945);

Page 133: c++

swap(‘a’,’c’);

getch();

}

Output:-

a value is: 9 b value is:3

a value is: 6.9 b value is:4.3

a value is: defg b value is: abcd

a value is: 4.321589 b value is: 4.369871

a value is: c b value is: a

**************************************

CLASS TEMPLATES:-

A class template is a class definition that describes a family of

related classes. C++ having the ability to create a class that

contains one or more types generic or parameterized class

templates.

Page 134: c++

By defining a class template the keyword template must be

inserted as a first word .

The general format for class template is as follows.

Template <class T>

Class class name

{

Data members;

Public:

Member function;

};

Class template definition is similar to a class definition.

Except the prefix template <class T>

This prefix tells the compiler that we are going to declare a

template and use T as a type name in the declaration.

41) Write a c++ program to demonstrate class template

concept?

Page 135: c++

#include<iostream.h>

#include<conio.h>

Template <class T>

Class myclass

{

Int I;

T a[10];

public:

void accept()

{

for(i=0;i<5;i++)

cin>>a[i];

}

void display()

{

for(i=0;i<5;i++)

cout<<a[i]<<” “;

Page 136: c++

}

};

void main()

{

clrscr();

myclass <int> x;

cout<<”enter 5 integers:”;

x.accept();

myclass <float> y;

cout<<”enter 5 float values:”;

y.accept();

cout<<”integers are”<<endl;

y.display();

getch();

}

Output:-

Page 137: c++

VIRTUAL FUNCTION (over loading):-

C++ provides a solution to invoke the exact version of the

number function which has to be decided at run time by using

virtual functions.

Using virtual functions the base class functions can be

overwrite in derived class.

A function can be defined as virtual by using the keyword

‘virtual’ and these are defined as public section of a class.

The general format for virtual function is given below.

Virtual return type <function name> (argument list)

{

Body of function;

}

Characteristics of virtual functions:-

Page 138: c++

The virtual function must be a member of a class

and they cannot be static.

These functions are accessed by pointer object.

A virtual function can be a friend to other class.

A virtual function in a base class must be

predefined (over loading) in a derived class.

A base class pointer can refer to derived class

object but the reverse is not possible.

42) Write a c++ program to demonstrate virtual function

concept?

#include<iostream.h>

#include<conio.h>

class base

{

public:

virtual void display()

{

Page 139: c++

cout<<”i am base”<<endl;

}

};

class derived : public base

{

public:

void display()

{

cout<<”i am derived”;

}

};

void main()

{

clrscr();

base *b,b1;

derived d1;

b=&b1;

Page 140: c++

b->display();

b=&d1;

b->display();

getch();

}

Output:-

i am base

i am derived

********************************************

INHERITANCE:-

C++ supports the concept of reusability that is c++ classes

can be reused in several ways. Once a class is written and

tested it can be reused by other programmers to suit their

requirements. This is done by creating new classes reusing the

properties of the existing once.

Definition of inheritance:-

Page 141: c++

The process of creating a new class from an existing class is

known as inheritance. The existing class is known as base

class or super class or parent class.

The newly created class is known as derived class or sub class

or child class.

The new class inherits all the capabilities of the existing class.

Advantages of inheritance:-

Inheritance permits the construction of reusable

components.

By using inheritance code sharing can occur at

several levels this gives the reusability of the

code and decreased maintenance cost because

sharing of the code by all the users.

Adding some enhancements to the base class

When multiple classes inherits from the same

parent class the behavior of inherited classes will

be the same.

Page 142: c++

FORMS (types):-

Inheritance is classified into the following forms based on the

levels of inheritance.

1) single inheritance

2) multiple inheritance

3) hierarchical inheritance

4) multilevel inheritance

5) hybrid inheritance

6) multi path inheritance

1) single inheritance :-

Derivation of a class from only one base class it is called

single inheritance.

Base

Derived

Page 143: c++

43) Write a c++ program by using single inheritance concept

print student details such as no, name, father name, marks,

total and average?

#include<iostream.h>

#include<conio.h>

class stddetails

{

protected:

int sno;

char sname[10],fname[10];

public:

void getdetails();

void printdetails();

};

class stumarks:public stddetails

{

Page 144: c++

int m1,m2,m3,tot;

float avg;

public:

void getmarks();

void cal();

void putmarks();

};

void stddetails::getdetails()

{

cout<<”enter sno sname fname:”;

cin>>sno>>sname>>fname;

}

void stddetails::printdetails()

{

cout<<”sno sname fname”<<endl;

cout<<sno<<” “<<sname<<” “<<fname<<endl;

}

Page 145: c++

void stumarks::getmarks()

{

stddetails::getdetails();

cout<<”enter marks”<<endl;

cin>>m1>>m2>>m3;

}

void stumarks::cal()

{

tot=m1+m2+m3;

avg=tot/3;

}

void stumarks::putmarks()

{

stddetails::printdetails();

cout<<”m1 m2 m3 tot avg”<<endl;

cout<<m1<<” “<<m2<<” “<<m3<<” “<<tot<<”

“<<avg<<endl;

Page 146: c++

}

void main()

{

clrscr();

stumarks s;

s.getmarks();

s.cal();

s.putmarks();

getch();

}

Output:-

Enter sno sname fname :

6

Tyu

Fgh

Enter marks:

45

Page 147: c++

67

58

Sno sname fname

6 tyu fgh

M1 m2 m3 total avg

45 67 58 170 56

****************************************

Multiple inheritance:-

Creating a new class from several base classes is called

multiple inheritance.

(or)

Derivation of a class from two or more base classes is called

multiple inheritance.

Page 148: c++

Base1 base2 base3

Derived

Multiple inheritance:-

#include<iostream.h>

#include<conio.h>

class base1

{

protected:

int a;

public:

void getdata();

Page 149: c++

};

class base2

{

protected:

int b;

public:

void getdata();

};

class derived:public base1, public base2

{

int c;

public:

void calc();

};

void base1::getdate()

{

cout<<”enter a value”<<endl;

Page 150: c++

cin>>a;

}

void base2::getdata()

{

cout<<”enter b value=”<<endl;

cin>>b;

}

void derived::calc()

{

base1::getdata();

base2::getdata();

c=a+b;

cout<<a<<” “<<b<<”=”<<c;

}

void main()

{

clrscr();

Page 151: c++

derived d;

d.calc();

}

Output:-

Enter a value: 6

Enter b value: 8

6 8 =14

**************************************

45) Write a c++ program by using multiple inheritance

concept to calculate the total marks of the student from first,

second and third tests. Subjects: physics, chemistry, maths?

Hierarchical inheritance:-

Creating more than one new class from a single base class is

called hierarchical inheritance.

(or)

Page 152: c++

Derivation of several classes from one base class that is one

class may be inherited by more than one class is called

hierarchical inheritance.

Base

Derived1 derived2

Page 153: c++