Top Banner
Course:- B.C.A & B.SC(IT) Date:-17-October-2006 SHAMMI KUMAR (B.C.A)
484

Programming In C++

May 06, 2015

Download

Education

shammi mehra

C++ has certain characteristics over other programming languages.
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: Programming In C++

Course:- B.C.A & B.SC(IT)

Date:-17-October-2006

SHAMMI KUMAR (B.C.A)

Page 2: Programming In C++

Chapter-1st

Page 3: Programming In C++

Software Crisis

Development in software technology continue to be dynamic. New tools and techniques are announced in quick succession. This has forced the software engineers and industry to continuously look for new approaches to software design and development, and they are becoming more and more critical in view of the increasing complexity of software systems as well as the highly competitive nature of the industry. These rapid advances appear to have created a situation

Page 4: Programming In C++

of crisis within the industry. The following issues need to be addressed to face this crisis:

How to represent real-life entities of problems in system design?

How to ensure reusability and extensibility of modules?

How to develop modules that are tolerant to any changes in future?

How to improve software productivity and decrease software cost?

Page 5: Programming In C++

How to improve the quality of software?

How to manage time schedules?

These studies and other reports on software implementation suggest that software products should be evaluated carefully for their quality before they are delivered and implemented. Some of the quality issues that must be considered for critical evaluation are:

Correctness

Maintainability

Page 6: Programming In C++

Reusability

Portability

Security

User friendliness

Procedure-Oriented ProgrammingIn the procedure-oriented approach,

the problem is viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. Procedure-oriented programming basically

Page 7: Programming In C++

consists of writing a list of instructions (or actions) for the computer to follow, and organizing these instructions into groups known as functions. We normally use a flowchart to organize these actions and represent the flow of control from one actions to another.

In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Figure below shows the relationship of data and functions in a procedure-oriented program.

Page 8: Programming In C++

Global data Global data

Function-1

Local data

Function-2

Local data

Function-3

Local data

Fig. Relationship of Data and Functions in Procedural Programming

Page 9: Programming In C++

Some characteristics exhibited by procedure-oriented programming are:

Emphasis is on doing things (algorithms).

Large programs are divided into smaller programs known as functions.

Most of the functions share global data.

Data move openly around the system from function to function.

Employs top-down approach in program design.

Page 10: Programming In C++

Object-Oriented Programming ParadigmThe major objective of Object-oriented

approach is to remove some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. The organization

Page 11: Programming In C++

of data and functions in object-oriented programs is shown in figure below. The data of an object can be accessed only by the functions associated with that object. However functions of one object can access the functions of other objects.

Some of the striking features of object-oriented programming are:

Programs are divided into what are known as objects.

Programs are divided into what are

Page 12: Programming In C++

known as objects.

• Functions that operate on the data of an object are tied together in the data structure.

• Data is hidden and cannot be accessed by external functions.

• Objects may communicate with each other through functions.

• New data and functions can be easily added whenever necessary.

Page 13: Programming In C++

Follows bottom-up approach in program design.

Data

Functions

Object A

Data

Functions

Object B

Functions

Data

Object C

Communication

Fig. Organization of data and functions in OOP

Page 14: Programming In C++

It is necessary to understand some of the concepts used extensively in object-oriented programming. These include:

1.Objects and Classes

2.Data abstraction and encapsulation

3.Inheritance

4.Polymorphism

Page 15: Programming In C++

5. Dynamic binding

6. Message passing

1 Objects and Classes:- Objects are the basic runtime entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program may handle. They may also represent user-defined data types such as vectors and list.Each data contains data and code to manipulate the data.

Page 16: Programming In C++

The entire set of data and code of an object can be made a user-defined data type using the concept of a class.A class may be thought of as a ‘data type’ and an object as a ‘variable’ of that data type.

For example Mango, Apple,and Orange are members of the class Fruit.

Page 17: Programming In C++

Person

Name

BasicPay

Salary ()

Tax ()

Object

Data

Methods

Fig. Representation of an Object

Page 18: Programming In C++

2. Data Abstraction and Encapsulation:- The wrapping up of data and methods into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class.

Abstraction refers to the act of representing essential features without including the background details or explanations.

3. Inheritance:- It is the process by which

Page 19: Programming In C++

objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. For example, the bird robin is a part of the class flying bird, which is again a part of the class bird. As illustrated in fig. below, the principle behind this sort of division is that each derived class shares common characteristics with which it is

Page 20: Programming In C++

derived. Bird

Attributes:

Feathers

Flying Bird

Attributes:

Nonflying Bird

Attributes:

RobinAttributes:

SwallowAttributes:

Pigeon

Attributes:

KiwiAttributes:

Page 21: Programming In C++

In OOP, the concept of 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.

4. Polymorphism:- Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. For example, an

Page 22: Programming In C++

operation may exhibit different behaviour in different instances. The behaviour depends upon the types of data used in the operation. For example, consider the operation of addition for two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. Figure below shows that a single function name can be used to handle different number and different types of

Page 23: Programming In C++

arguments.Shape

Draw ( )

Circle Object

Draw ( )

Box Object

Draw ( ) Draw ( )

Triangle Object

Fig. Polymorphism

Page 24: Programming In C++

Dynamic Binding:- Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at runtime.

6. Message Communication:- An object-oriented program consists of a set of objects that communicate with each

Page 25: Programming In C++

other. The process of programming in an object-oriented language, therefore, involves the following basic steps:

1. Creating classes that define objects and their behaviour.

2. Creating objects from class definitions.

3. Establishing communication among objects.

Objects communicate with one another

Page 26: Programming In C++

by sending and receiving information much the same way as people pass messages to one another as shown in fig. below

Object 1

Object 5

Object 2

Object 4 Object 3

Fig. Network of objects communicating between them

Page 27: Programming In C++

Message passing involves specifying the name of the object, the name of the method (message) and the information to be sent. For example, consider the statement

Employee. Salary (name);

Here, Employee is the object, salary is the message and name is the parameter that contains information.

Page 28: Programming In C++

OOP offers several benefits to both the program designer and the user.The principle advantages are:

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

We can build programs from the standard

Page 29: Programming In C++

working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity.

The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program.

Message passing techniques for

Page 30: Programming In C++

communication between objects make the interface descriptions with external systems much simpler.

Software complexity can be easily managed.

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

Page 31: Programming In C++

Object-Oriented Languages

The languages should support several of the OOP concepts to claim that they are object-oriented. Depending upon the features they support, they can be classified into the following two categories:

1. Object-based programming languages, and

2. Object-oriented programming languages.

Object-based programming is the style of

Page 32: Programming In C++

programming that primarily supports encapsulation and object identity. Major features that are required for object-based programming are:

Data Encapsulation

Data hiding and access mechanisms

Automatic initialization and clear-up of objects

Operator overloading

Languages that support programming with objects are said to be object-based

Page 33: Programming In C++

programming languages. They do not support inheritance and dynamic binding. Ada is a typical object-based programming language.

Object-Oriented programming incorporates all of object-based programming features along with two additional features, namely, inheritance and dynamic binding. Object-oriented programming can therefore be characterized by the following statement:

Object-based features + Inheritance + Dynamic binding

Page 34: Programming In C++

Applications of OOP

There appears to be a great deal of excitement and interest among software engineers in using OOP. Applications of OOP are beginning to gain importance in may areas. The most popular application of object-oriented programming has been in the area of user interface design such as windows. OOP is useful in these types of applications because it can simplify a complex problem. The promising areas for application of OOP include:

Page 35: Programming In C++

• Object-Oriented Databases

•AI and Expert Systems

• Decision support and office Automation Systems

It is believed that the richness of OOP environment will enable the software industry to improve not only the quality of software systems but also its productivity. Object-Oriented technology is certainly going to change the way the software engineers think, analyze, design and implement future systems.

Page 36: Programming In C++

Chapter-2nd

Page 37: Programming In C++

What is C++C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s. Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best of both the languages and create a more powerful language that could support object-oriented programming features and still retain the power and elegance of C. The result was C++. Therefore, C++ is an extension of C with a major addition of the class construct feature of Simula67. Since the class

Page 38: Programming In C++

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 (incremented) version of C.

During the early 1990’s the language underwent a number of improvements and changes. In November 1997, the ANSI/ISO standards committee standardised these changes and added several new features to the language specifications.

Page 39: Programming In C++

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

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, thereby making C++ a truly object-oriented language.

Page 40: Programming In C++

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

Since C++ allows us to create hierarchy-related objects, we can buildspecial object-oriented libraries which can be used later by many programmers.

Applications of C++

Page 41: Programming In C++

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.

A Simple C++ Program

#include<iostream> // include header file

int main( )

Page 42: Programming In C++

{

cout<<“C++ is better than c.\n”; // C++ statement

return o;

} // end of example

The simple program demonstrates several C++ features.

• Program Features :- Like C, the C++ program is a collection of functions. The above example contains only one function, main( ). As usual, execution begins at main( ). Every C++ program

Page 43: Programming In C++

must have a main(). Like C, the C++ statement terminate with semicolons.

• Comments :- C++ introduces a new comment symbol // (double slash). Comments start with a double slash symbol and terminate at the end of the line. A comment may start anywhere in the line, and whatever follows till the end of the line is ignored.

The double slash comment is basically a single line comment. Multiline comments can be written as follows:

// This is an example of

Page 44: Programming In C++

// C++ program to illustrate

// Some of its features

The C comment symbols /*,*/ are still valid and are more suitable for multiline comments.

The following comment is allowed:

/* This is an example of

C++ program to illustrate

Some of its features

*/

Page 45: Programming In C++

• Output Operator :- The statement

cout<<“C++ is better than C.”;

Causes the string in quotation marks to be displayed on the screen. This statement introduces two new C++ features, cout and <<. The identifier cout (pronounced as ‘C out’) is a predefined object that represents the standard output stream in C++.

The operator << is called the insertion or put to operator. It inserts (or sends) the contents of the variable on its right to the object on its left.

Page 46: Programming In C++

Cout << “C++”

Screen

Object

Insertion Operator

Variable

Fig. Output using Insertion Operator

Page 47: Programming In C++

• The iostream File :- We have used the following #include directive in the program:

#include<iostream>

This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator <<. Some old versions of C++ use a header file called iostream.h. This is one of the changes introduced by ANSI C++.(We should use iostream.h if the compiler does not support ANSI C++ features.)

The header file iostream should be included at

Page 48: Programming In C++

the beginning of all programs that use input/output statements. We must include appropriate header files depending on the contents of the program and implementation.

• Return Type of main() :- In C++, main() returns an integer type value to the operating system. Therefore, every main () in C++ should end with a return(0) statement; otherwise a warning or an error might occur. Since main() returns an integer type value, return type for main() is explicitly specified as int.

Note:- The default return type for all functions in C++ is int.

Page 49: Programming In C++

The following main without type and return will run with a warning:

main()

{

--------

--------

}

Page 50: Programming In C++

More C++ Statements

#include<iostream>

int main()

{

float number1, number2, sum, average;

cout<<“Enter two numbers:”;

cin>>number1;

cin>>number2;

sum=number1+number2;

Page 51: Programming In C++

average=sum/2;

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

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

return 0;

}

Structure of C++ Program

A typical C++ program would contain four sections as shown in fig. Below. These sections may be placed in separate code files and then compiled independently or jointly.

Page 52: Programming In C++

It is a common practice to organize a program into three separate files. The class declarations

Include files

Class declaration

Member function definitions

Main function program

Fig. Structure of a C++ program

Page 53: Programming In C++

are placed in a header file and the definitions of member functions go into another file. This approach enables the programmer to separate the abstract specification of the interface (class definition) from the implementation details (member functions definition). Finally, the main program that uses the class is placed in a third file which “includes” the previous two files as well as any other files required.

This approach is based on the concept of client-server model as shown in fig. below. The class definition including the member functions constitute the server that provides services to the

Page 54: Programming In C++

main program known as client. The client uses the server through the public interface of the class

Member functions

Class definition

Server

Main function program Client

Fig. The client-server model

Page 55: Programming In C++

Creating The Source File

Like C programs, C++ programs can be created using any text editor. For example, on the INIX, we can use vi or ed text editor for creating and editing the source code. On the DOS system, we can use editor or any other editor or a word processor system under non-document mode.

Some systems such as Turbo C++ provide an integrated environment for developing and editing programs.

The file name should have a proper file

Page 56: Programming In C++

extension to indicate that it is a C++ program file. C++ implementations use extensions such as .c, .C, .cc, .cpp and .cxx. Turbo C++ and Borland C++ use .c for C programs and .cpp for C++ programs. Zortech C++ systems uses .cxx while UNIX AT&T version uses .C and .cc. The operating system manuals should be consulted to determine the proper file name extensions to be used.

Page 57: Programming In C++

Compiling and Linking

The process of compiling and linking again depends upon the operating system. A few popular systems are discussed in this section.

Unix AT&T C++ :- The process of implementation of a C++ programs under UNIX is similar to that of a C program. We should use the “CC” (uppercase) command to compile the program. Remember we use lowercase “cc” for compiling C programs.

Page 58: Programming In C++

Turbo C++ and Borland C++ :- It provide an integrated program development environment under MS DOS. They provide a built-in editor and a menu bar which includes options such as File, Edit, Compile and Run.

Visual C++ :- It a Microsoft application development system for C++ that runs under Windows. Visual C++ is a visual programming environment in which basic program components can be selected through menu choices, buttons, icons and other predetermined methods.

Page 59: Programming In C++

Chapter-3rd

Page 60: Programming In C++

C++ is a superset of C and therefore most constructs of C are legal in C++ with their meaning unchanged. However, there are some exceptions and additions.

Tokens

The smallest individual units in a program are known as tokens. C++ has the following tokens:

• Keywords

Page 61: Programming In C++

• Identifiers

• Constants

• Strings

• Operators

Keywords:- The keywords are also the identifiers but can’t be user-defined since they are reserved words. The following words are reserved for use as keywords. We should not choose them as variables or identifiers. It is mandatory that all keywords be in lowercase letters.

int, long, float, auto, class, char, static, private,

Page 62: Programming In C++

switch, long, return, goto, short, throw, while, inline, friend, extern, catch, enum, else, default, protected, new, signed, etc.

Identifiers:- It can be defined as the name of the variables and some other program elements using the combinational of following characters.

Alphabets----- a-z, A-Z

Numerals----- 0-9

Underscore----- _

Constants:- There are three types of constants:-

Page 63: Programming In C++

1. String Constant

2. Numeric Constant

3. Character Constant

String Constant:- String constant is a sequence of alphanumeric characters enclosed in double quotation marks whose maximum length is 256 characters.

Numeric constants:- There are the +ve and –ve numbers.

There are four types of numeric constants:- integer constants, floating constants,

Page 64: Programming In C++

hexadecimal constants and octal constants. An integer may either be short and long integer.

A floating point constant may be either single or double.

• Integer constant:- It don't contain decimal points. Variables can be declared as integers in the following ways:

Data types Size

int 2-4 bytes

short int 2 bytes

long int 4 bytes

Page 65: Programming In C++

• Floating point constants:- It consists of +ve and –ve numbers but in decimal form. Floating point consists of three data types: float, double, long double.

The floating point types and its size in C++ are given in the following table:

Data types Size

float 4 bytes

double 8 bytes

long double 12-16 bytes

Page 66: Programming In C++

• Hexadecimal Constants:- Hexadecimal numbers are integer numbers of base 16 and their digits are 0-9 and A to F. Any hexadecimal number characterized in the hexadecimal constant groups. In C++ it is normally represented using the character x.

• Octal Constants:- Octal numbers are the integer numbers of base 8 and their digits are 0-7. Any octal number is characterized in the octal constant group.

Character Constants:- The character constants are represented within the single quotes.

Page 67: Programming In C++

For Example: ‘A’, ‘a’ etc.

Basic Data Types

Data types are those keywords which shows what type of variables we are going to declare. Data types used in C++ area re as under:-

1. Integer Data types:- Integer data types consists of integer values I.e non-zero values. There are three types of Integer data types.

Data types Size

int 2-4 bytes

short int 2 bytes

Page 68: Programming In C++

long int 4 bytes

2. Float data types:- Floating point data types are used to declare variables of floating types. Variables of floating types. Variables of floating types consists of values having a decimal in it. Floating values are both in +ve and –ve form. There are three types of floating data types: float, double and long double.

Data types Size

float 4 bytes

double 8 bytes

Page 69: Programming In C++

long double 12-16 bytes

3. Character Data types:- Any character belonging to the ASCII character set is considered as a character data type whose size is 8 bits long. The character is a keyword to represent the character data types in C++

For Example:- char ‘c’.

Page 70: Programming In C++

User-Defined Data Types

Structures and Classes:- C++ also permits us to define another user-defined data type known as class which can be used, just like any other basic data type, to declare variables. The class variables are known as objects, which are the central focus of object-oriented programming.

Enumerated Data Type:- It is another user-defined type which provides a way for attaching names to numbers, thereby increasing comprehensibility of the code. The enum keyword (from C) automatically enumerates a

Page 71: Programming In C++

list of words by assigning them values 0,1,2 and so on. This facility provides an alternative means for creating symbolic constants. The syntax of an enum statement is similar to that of the struct statement.

Examples:

enum shape{circle,square,triangle};

enum colour{red,blue,green,yellow};

enum position{off,on};

Page 72: Programming In C++

Derived Data Types

Arrays:- The application of arrays in C++ is similar to that in C. The only exception is the way character arrays are initialized. When initializing a character array in ANSI C, the compiler will allow us to declare the arrays size as the exact length of the string constant. For instance,

char string[3]=“xyz”;

is valid in ANSI C. It assumes that the programmer intends to leave out the null character \0 in the definition. But in C++, the size

Page 73: Programming In C++

should be one larger that the number of characters in the string.

char string[4]=“xyz”; //O.K. for C++

Functions:- Functions have undergone major changes in C++. While some of these changes are simple, others require a new way of thinking when organizing our programs. Many of these modifications and improvements were driven by the requirements of the object-oriented concept of C++.

Pointers:- A data type that holds the address of a location in memory. Pointers are extensively

Page 74: Programming In C++

used in C++ for memory management and achieving polymorphism.

Symbolic Constants

There are two ways of creating symbolic constants in C++:

• Using the qualifier constant, and

• Defining a set of integer constants using enum keyword.

In both C and C++, any value declared as const cannot be modified by the program in any

Page 75: Programming In C++

way. However, there are some differences in implementation. In C++, we can use const in a constant expression, such as

const int size=10;

Another method of naming integer constants is by enumeration as under;

enum{x,y,z};

This defines x,y and z as integer constants with values 0,1 and 2 respectively. This is equivalent to:

const x=0;

Page 76: Programming In C++

const y=1;

const z=2;

Declaration of Variables

C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write and reduces the errors that may be caused by having to scan back and forth. It also makes the program easier to understand because the variables are declared in the context of their use.

Page 77: Programming In C++

The example below illustrates this point.

#include<iostream.h>

#include<conio.h>

int main()

{

float x; // declaration

float sum=0;

for(int i=1;i<5;i++) // declaration

{

Page 78: Programming In C++

cin>>x;

sum=sum+x;

}

float average; // declaration

average=sum/i;

cout<<average;

getch();

return 0;

}

Page 79: Programming In C++

Dynamic Initialization of Variables

C++, however, permits initialization of the variables at run time. This is referred to as dynamic initialization. In C++, a variable can be initialized at run time using expressions at the place of declaration.

For example

Float area=3.14*rad*rad;

Page 80: Programming In C++

Reference Variables

C++ introduces a new kind of variable known as the reference variable. A reference variable provides an alias (alternative name) for a previously defined variable. For example, if we make the variable sum a reference to the variable total, then sum and total can be used interchangeably to represent that variable. A reference variable is created as follows:

Syntax:

data-type & reference-name= variable-name

Page 81: Programming In C++

Example: 1.

float total=100;

float sum=total;

2. int n[10];

int &x=n[10]; // x is alias for n[10]

Operators in C++

The different types of operators and their usage in C++ are explained in the following sections. There are some unusual operators making unlike the other high level languages

Page 82: Programming In C++

1. Arithmetic Operators

2. Assignment operators

3. Comparison operators

4. Logical operators (Relational, Equality, Logical)

5. Special operators (Unary, Ternary, Comma, Scope, new and delete, other operators)

Page 83: Programming In C++

3. Comparison Operators:- The comparison operators can be grouped into three categories. They are the Relational operators, Equality operators and Logical operators.

a). Relational Operators:- It compare the values to see if they are equal or if one of them is greater than the other and so on.

Operators Meaning

< Less than

> Greater than

<= Less than equal to

Page 84: Programming In C++

>= Greater than equal to

b). Equality Operators:- Equality operators are used to check the equality of the given expression.

Operators Meaning

== Equal to

!= Not equal to

C). Logical Operators:- There are three logical operators used in C++, AND, OR and NOT.

• Logical AND:- A compound expression is true when two conditions are true. The results of an

Page 85: Programming In C++

AND logical operators are as under:-

Situation Results

True && True True

True && False False

False && True False

False && False False

• Logical OR:- In logical Or if one or both the conditions are satisfied then the result is true.

Situation Results

True||True True

Page 86: Programming In C++

True||False True

False||True True

False||False False

• Logical NOT:- Logical NOT can changed the condition from true to false and false to true.

Situation Results

!(True) False

!(False) True

4. Special Operators:- These are special type of operators used in C++ language to perform

Page 87: Programming In C++

4. particulars function.

• Unary Operators:- The unary operators require only a single expression to produce a line. Unary operators usually precede their single operands. Sometimes some unary operators may be followed by the operands such as incremental and decremental.

Operators Meaning

-- Decrement

++ Increment

Page 88: Programming In C++

* The pointer operator is used to get

the content of the address

& Address operator is used to get the

address of the variable.

• Cast Operators:- This operators is used to convert one data type to another

• Ternary Operator

• Comma Operator

• Scope Operator:- The double colon is used as the scope resolution operator in C++.

Page 89: Programming In C++

• New and Delete Operator:- New operator is used for giving memory allocation to an object and delete is used to remove the memory allocation of an object.

Scope Resolution Operator

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

Page 90: Programming In C++

---------

{

int x=10;

------

------

{

int x=1;

--------

--------

}

---------

}

Block 1

Block 2

Page 91: Programming In C++

Block 2 is contained in block 1.

Note:- A declaration in an inner block hides a declaration of the same variable in an outer block and, therefore, each declaration of x causes it to refer to a different data object. Within the inner block, the variable x will refer to the data object declared therein.

In C, the global version of a variable cannot be accessed from with in the inner block. C++ resolves this problem by introducing a new operator :: called the scope resolution operator. This can be used to uncover a hidden variable. It takes the following form:

Syntax:- ::variable_name

Page 92: Programming In C++

Program on Scope Resolution Operator

#include<iostream.h>

#include<conio.h>

int m=10; //global m

int main()

{

int m=20; //m redeclared, local to main

{

int k=m;

Page 93: Programming In C++

int m=30; //m declared again

// local to inner block

cout<<“We are in inner block\n”;

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

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

cout<<“::m=“<<::m<<“\n”;

}

cout<<“\n we are in outer block\n”;

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

Page 94: Programming In C++

cout<<“::m=“<<::m<<“\n”;

getch()

return 0;

}Memory Management Operators

C uses malloc() and calloc() functions to allocate memory dynamically at run time. Similarly, it uses the function free() to free dynamically allocated memory. We use dynamic allocation techniques when it is not known in advance how much of memory space is needed. Although C++ supports these functions, it also defines two unary operators new and delete that

Page 95: Programming In C++

perform the task of allocating and freeing the memory in a better and easier way.

1. New:- The new operator is used to create heap of memory space for an object of a class. The allocation is carried out as:-

a)Storage for object is found.

b)Object is initialized.

c) A suitable pointer to the object is returned.

If the ‘New’ operator is successful a pointer to the space is returned otherwise it returns the value zero.

Syntax:- data_type pointer=new data_type

Page 96: Programming In C++

For example:-

int *p=new int;

2. Delete:- The delete operator is used to destroy the space for the variable which has been created by using the new operator. In reliability, the delete keyword calls upon the function operator delete( ).

Syntax:- delete pointer_variable;

For example:- delete p;

Page 97: Programming In C++

Manipulators

Manipulators are operators that are used to format the data display. The most commonly used manipulators are endl and setw.

The endl manipulator, when used in an output statement, causes a linefeed to be inserted. It has the same effect as using the newline character “\n”.

For example:-

cout<<“m=“<<m<<endl;

Page 98: Programming In C++

The manipulator setw specifies a field width for printing the value of the variable. This value is right-justified within the field.

Program on Manipulators:-

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

int main()

{

int basic=950,allowance=95,total=1045;

Page 99: Programming In C++

cout<<setw(5)<<“basic”<<setw(5)<<basic<<endl

<<setw(5)<<“allowance”<<setw(5)<<allowance<<endl

<<setw(5)<<“total”<<setw(5)<<total<<endl;

getch();

return 0;

}

Type Cast Operator

Conversion by using the assignment operator is carried out automatically but one may not get the desired results.

The cast operator is a technique to forcefully

Page 100: Programming In C++

convert one data type to another. The operator used for type casting is called as the cast operator and the process is called as casting.

Syntax:-

(cast_type) expression;

or

cast_type (expression);

Page 101: Programming In C++

Expressions and their Types

An expression is a combination of operators, constants and variables arranged as per the rules of the language. It may also include function calls which return values. An expression may consist of one or more operands , and zero or more operators to produce a value. Expressions may be of the following seven types:

• Constant expressions

• Integral expressions

• Float expressions

• Pointer expressions

Page 102: Programming In C++

•Relational expressions

• Logical expressions

• Bitwise expressions

An expression may also use combination of the above expressions. Such expressions are known as compound expressions.

Constant Expressions:- It consist of only constant values.

Integral Expressions:-These are those which produce integer results after implementing all the automatic and explicit type conversions.

Page 103: Programming In C++

Float Expressions:- These are those which, after all conversions, produce floating-point results.

Pointer Expressions:- These expressions produce address values.

Relational Expression:- Relational expressions yield results of type bool which takes a value true or false.

Examples:- x<=y

a+b==c+d

m+n>100

When arithmetic expression are used on either side of a relational operator, they will be evaluated first and then

Page 104: Programming In C++

the results compared. Relational expressions are also known as Boolean expressions.

Logical Expressions:- Logical expressions combine two or more relational expressions and produces bool type results. Examples:

a>b && x==10;

x==10 || y==5

Bitwise Expressions:- These are used to manipulate data at bit level. They are basically used for testing or shifting bits. Examples:

x<<3 //shift three bit position to left

Page 105: Programming In C++

y>>1 //shift one bit position to right

Special Assignment Expressions

1. Chained Assignment:-

x=(y=10);

or

x=y=10;

First 10 is assigned to y and then to x.

A chained statement cannot be used to initialize variables at the time of declaration.

Page 106: Programming In C++

For instance, the statement

float a=b=12.34 //wrong

is illegal. This may be written as

float a=12.34, b=12.34 //correct

2. Embedded Assignment:-

x=(y=50)+10;

(y=50) is an assignment expression known as embedded assignment. Here, the value 50 is assigned to y and then the result 50+10=60 is assigned to x. This statement is identical

Page 107: Programming In C++

y=50;

x=y+10;

3. Compound Assignment:- Like C, C++ supports a compound assignment operator which is a combination of the assignment operator with a binary arithmetic operator. For example, the simple assignment statement

x=x+10;

may be written as

x+=10;

The operator += is known as compound

Page 108: Programming In C++

assignment operator or short-hand assignment operator.

Implicit Conversions

We can mix data types in expressions. For example,

m=5+2.75;

is valid statement. Wherever data types are mixed in an expression, C++ performs the conversion automatically. This process is known as implicit or automatic conversion.

Page 109: Programming In C++

Operator Overloading

The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. The behaviour depends upon the types of data used in the operation. For example:- Consider the operation of addition for two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The main advantage of using an overloading operator in a program are that is much easier to read and debug.

Page 110: Programming In C++

Operator Precedence

Although C++ enables us to add multiple meanings to the operators, yet their association and precedence remain the same. For example, the multiplication operator will continue having higher precedence than the add operator.

Control Structures

Page 111: Programming In C++

Chapter-4th

Page 112: Programming In C++

IntroductionFunctions play an important role in program development. Dividing a program into functions is one of the major principles of top-down, structured programming. Another advantage of using functions is that it is possible to reduce the size of a program by calling and using them at different places in the program.

Syntax:-

void show(); /*Function declaration*/

main()

Page 113: Programming In C++

{

------

show(); /*function call*/

-------

}

void show() /*function definition*/

{

--------

-------- /*function body*/

---------

}

Page 114: Programming In C++

Function Prototyping

Function prototyping is one of the major improvements added to C++ functions. The prototype describes the function interface to the compiler by giving details such as the number and type of arguments 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

Page 115: Programming In C++

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

Syntax:-

type function_name(argument_list);

For Example:-

float volume(int x,float y,float z);

Page 116: Programming In C++

Call By Reference

Whenever a function with formal arguments is invoked, the address of the actual arguments are copied into the formal arguments though they have different variable names. Now if the arguments are changed in the formal function, they will be returned to the calling function in altered form, as the formal and actual arguments have the same memory location. Hence when the arguments are passed to the formal function by reference, it means that their address is passed and

Page 117: Programming In C++

so any change that is made in the formal function will change the calling function.

For Example:-

void main()

{

int a=10,b=20;

swap(&a, &b);

cout<<a<<b;

}

Page 118: Programming In C++

swap(int *x, int *y)

{

int=temp;

temp=*x;

*x= *y;

*y=temp;

getch();

}

Page 119: Programming In C++

Default Arguments

C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared.

For example:-

void main()

{

float amount();

Page 120: Programming In C++

float value(int p,int b,float r=5.13);

amount=value(50,5);

cout<<“\nfinal value=“<<amount<<“\n;

}

float value(int p,int n,float r)

{

float temp;

temp=p+n+r;

cout<<“sum=“<<temp;

Page 121: Programming In C++

getch();

return(temp);

}Function Overloading

It is a logical method of calling several functions with different arguments and data types that perform basically identical things by same name. Its main advantages are:-

Elimination of use of different function names for same operations.

Helps to understand, debug and grasp easily.

Page 122: Programming In C++

Easy maintenance of the data.

The function declaration and function definition are essential for each function with same name but different arguments.

Function Overloading with various Data types

It allows to use the same function name for various data types. The function declaration,definition and function call are done with the same name but different data arguments.

The correct name will be selected by C++

Page 123: Programming In C++

compiler for comparing the types of actual parameters with formal parameters.

Function Overloading with Arguments

A function can also be overloaded for number of arguments in the function call.

Scoping Rules for Function Overloading

The overloading mechanism is acceptable only within the same scope of the function declaration. The same function name in various classes is not said to be overloaded.

Page 124: Programming In C++

Program on Function Overloading:-

void main()

{

int square(int);

float square(float);

int x, xsqr;

float y, ysqr;

cout<<“Enter x and y”;

cin>>x>>y;

Page 125: Programming In C++

xsqr=square(x);

cout<<xsqr;

ysqr=square(y);

cout<<ysqr;

}

int square(int a)

{

return(a*a);

}

Page 126: Programming In C++

float square(float a)

{

return(a*a);

}

getch();

}

Friend Function

Friend function are the functions that are used to have an access to the data members that are declared in a private category of a class. Friend is

Page 127: Programming In C++

a special mechanism for letting a non-member function access private data. A friend function may be either declared are defined within the scope of a class definition. The keyword “friend” informs the compiler that is it not a member function of the class. The general syntax is:-

friend return_type function_name(arguments);

A friend function has the following characteristics:-

• It is not in the scope of the class to which is has been declared as friend.

Page 128: Programming In C++

• Since it is not in the scope of the class, it cannot be called using the object of that class.

• It can be invoked like a normal function without the help of any object. Usually it has the objects as arguments.

• It can be declared either in private or public part of the class without affecting its meaning.

• Unlike member function, it cannot access the member names directly and has to use an object name and dot membership operator with each member name (e.g a.x).

Page 129: Programming In C++

Program on Friend Function:-

class sample

{

int x;

public:

void getdata();

friend void display(sample);

};

void sample::getdata()

Page 130: Programming In C++

{

cout<<“Enter a value of x”;

cin>>x;

}

void display(sample s)

{

cout<<“Entered no. is”;

cout<<s.x;

cout<<endl;

Page 131: Programming In C++

}

void main()

{

sample s;

s.getdata();

display(s);

getch();

}

Page 132: Programming In C++

Inline Functions

It is used only in function declaration to give a hint to the compiler that inline substitution of the function body is to be preferred to usual function call implementation.

Syntax:-

class class_name

{

various sections

Page 133: Programming In C++

inline return_type functionname (argument list)

}

Advantages:-

• The size of the object code is reduced.

• The speed of execution is increased.

• These are compact function calls.

Page 134: Programming In C++

Program on Inline Functions:-

inline int mul(int x,int y)

{

return(x*y);

}

inline int div(int p,int q)

{

return(p/q);

Page 135: Programming In C++

}

int main()

{

int a=9;

int b=9;

clrscr();

cout<<mul(a,b)<<“\n”;

cout<<div(a,b)<<“\n”;

Page 136: Programming In C++

getch();

return 0;

}

Virtual FunctionA virtual function is one that does not really exist but it appears real in some parts of a program. 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.

To make a member function virtual, the

Page 137: Programming In C++

keyword virtual is used in the method while it is declared in the class definition but not in the member function definition. The compiler gets information from the keyword virtual that it is virtual function and not a conventional functional declaration.

The general syntax of the virtual function declaration is:

class class_name

{

private:

Page 138: Programming In C++

statements;

public:

virtual return_type function_name(arguments);

};

For example:

class base

{

public:

void display()

Page 139: Programming In C++

{

cout<<“Display base”;

}

virtual void show()

{

cout<<“Show base”;

}

};

class derived:public base

Page 140: Programming In C++

{

public:

void display()

{

cout<<“Display derived”;

}

void show()

{

cout<<“Show derived”;

Page 141: Programming In C++

}

};

void main()

{

base b;

derived d;

base *ptr;

ptr=&b;

(*ptr).display();

Page 142: Programming In C++

(*ptr).show;

ptr=&d;

(*ptr).display();

(*ptr).show();

getch();

}

Page 143: Programming In C++

Chapter-5th

Page 144: Programming In C++

Class

A class is a derived data type that groups related data items called data members and the functions called member functions that operate on data members.

Syntax:-

class class_name

{

private:

data member declaration;

Page 145: Programming In C++

member function declarations;

public:

data member declarations;

member function declarations;

};

The variables declared inside the class known as data members and the functions are known as member functions. These functions and variables are collectively called class members. They are usually grouped under two sections:-

Private and public.

Page 146: Programming In C++

Thus a class is a technique to bind the data and the associated functions together. This binding of data and functions in the form of a class is known as Encapsulation.

The keywords private, protected and public are used to specify the three levels of access protection for hiding data and function members internal to the class.

• Private scope:- In this section, a member data can only be accessed by the member functions and friends of this class. The member functions and friends of this class can always read or write

Page 147: Programming In C++

private data members. The private data members are not accessible to the outside world.

•Protected scope:- In this section, a member data can only be accessed by the member functions and friends of this class. Also, these functions can be accessed by the member functions and friends derived from this class. It is not accessible to the outside worlds.

• Public scope:- The members which are declared in the public section, can be accessed by any function in the outside world (out of the class).

Page 148: Programming In C++

Program:-

class student

{

public:

int rollno;

char name[10];

void display()

{

cout<<“Enter your name”;

Page 149: Programming In C++

cin>>name;

cout<<“\n Enter your RollNo”;

cin>>rollno;

}

};

void main()

{

student s;

cout<<“Enter name and RollNo”;

Page 150: Programming In C++

cin>>s.name;

cin>>s.rollno;

cout<<“s.name and s.rollno”;

}

void display()

{

cout<<“name”<<name;

cout<<“Rollno”<<rollno;

}

Page 151: Programming In C++

};

Defining Member Functions

The member functions of a class are also called class functions. These functions may be defined in two ways:-

• Inside the class declaration, called as inline functions.

Example:-

class item

{

Page 152: Programming In C++

int number;

float cost;

public:

void putdata(int a,int b)

{

cout<<“enter the values of a and b”;

cin>>a>>b;

}

};

Page 153: Programming In C++

• Outside the class declaration, with function declaration in the class.

Syntax:-

datatype specifier classname:: functionname (List of arguments)

{

function body

}

1. While defining a function outside the class, the function prototype must be declared within the class declaration.

Page 154: Programming In C++

2. The appearance of class name before the function name allows a user to use identical function names for different classes, because the class name limits the scope of the function to the specified class.

Nesting of Member Functions

A member function of a class can be called only by an object of the class using a dot operator. However, there is an exception to this. A member function can be called by using its name inside another member function of the same class. This is known as nesting of member function.

Page 155: Programming In C++

class set

{

int m,n;

public:

void input();

void display();

int largest();

};

int set::largest()

Page 156: Programming In C++

{

if(m>=n)

return(m);

else

return(n);

}

void set::input()

{

cout<<“Input values of m and n\n”;

Page 157: Programming In C++

cin>>m>>n;

}

void set::display()

{

cout<<“\nlargest value=“<<largest();

}

int main()

{

set a;

Page 158: Programming In C++

a.input();

a.display();

return 0;

}Static Data Members

The static variables are automatically initialized to zero unless these are initialized explicitly. In C++, these are of two types I.e static data member and static member function.

Properties of Static data members:-

The access rule of a static data member is

Page 159: Programming In C++

same as that of normal data member.

Whenever a static data member is declared it will be shared by all instance of the class.

The static data members should be created and initialized before the main function.

Properties of static member function:-

It can manipulate only one the static data members of the class.

It acts as global for members of its class.

It can’t be a virtual function.

Page 160: Programming In C++

It is also not a part of the objects of the class.

Program on static data member:-

class sample

{

static int count;

public:

sample();

void display();

};

Page 161: Programming In C++

int sample::count=0;

sample::sample

{

++count;

}

void sample::display()

{

cout<<“Counter value=“<<count<<endl;

}

Page 162: Programming In C++

void main()

{

sample obj1,obj2;

obj2.display();

}

Program on Static member function:-

class sample

{

static int count;

Page 163: Programming In C++

public:

sample();

static void display();

};

int sample::count=0;

sample::sample()

{

++count;

}

Page 164: Programming In C++

void sample::display()

{

cout<<count;

}

void main()

{

sample::display();

sample obj1,obj2,obj3;

sample::display();

Page 165: Programming In C++

getch();

}Arrays of Objects

An array can be of any data type including struct. Similarly, we can also have arrays of variables that are of the type class. Such variables are called arrays of objects.

For Example:-

class employee

{

char name[30];

Page 166: Programming In C++

float age;

public:

void getdata();

void putdata();

};

void employee::getdata()

{

cout<<“Enter name:”;

cin>>name;

Page 167: Programming In C++

cout<<“Enter age:”;

cin>>age;

}

void employee::putdata()

{

cout<<“name:”<<name<<“\n”;

cout<<“age:”<<age<<“\n”;

}

const int size=2;

Page 168: Programming In C++

int main()

{

employee manager[size];

for(int i=0;i<size;i++)

{

cout<<“\nDetails of manager”<<i+1;<<“\n”;

manager[i].getdata();

}

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

Page 169: Programming In C++

{

cout<<“\nManager”<<i+1<<“\n”;

manager[i].putdata();

}

getch();

return 0;

}

Page 170: Programming In C++

Memory Allocation For Objects

We have stated that the memory space for objects is allocated when they are declared and not when the class is specified. This statement is only partly true. Actually, the member functions are created and placed in the memory space only once when they are defined as a part of a class specification. Since all the objects belonging to that class use the same member functions, no separate space is allocated for member functions when the objects are created. Only space for member variables is allocated separately for each

Page 171: Programming In C++

object. Separate memory locations for the objects are essential, because the member variables will hold different values for different objects.

Objects As Function ArgumentsLike any other data type, an object may be

used as a function argument. This can be done in two ways:

A copy of the entire object is passed to the function.

Only the address of the object is transferred to the function

Page 172: Programming In C++

The first method is called pass-by-value. Since a copy of the object is passed to the function, any changes made to the object inside the function do not affect the object used to call the function.

The second method is called pass-by-reference. When an address of the object is passed, the called function works directly on the actual object used in the call. This means that any changes made to the object inside the function will reflect in the actual object. The pass-by-reference method is more efficient since it requires to pass only the address of the object and not the entire object.

Page 173: Programming In C++

Program on call-by-value:-

void main()

{

int x,y;

void swap(int,int);

x=100;

y=20;

cout<<“Values before swap()”<<endl;

cout<<“x=“<<x<<“and y=“<<y<<endl;

Page 174: Programming In C++

swap(x,y); //call by value

cout<<“values after swap()”<<endl;

cout<<“x=“<<x<<“and y=“<<y<<endl;

}

void swap(int x,int y) //values will not be swapped

{

int temp;

temp=x;

x=y;

Page 175: Programming In C++

y=temp;

}

Program on pass-by-reference:-

void main()

{

int x,y;

void swap(int *x,int *y);

x=100;

y=20;

Page 176: Programming In C++

cout<<“Values before swap()”<<endl;

cout<<“x=“<<x<<“and y=“<<y<<endl;

swap(&x,&y); //call by reference

cout<<“values after swap()”<<endl;

cout<<“x=“<<x<<“and y=“<<y<<endl;

}

void swap(int *x,int *y) //Values will be swapped

{

int temp;

Page 177: Programming In C++

temp=*x;

*x=*y;

*y=temp;

}

Returning Objects

A function cannot only receive objects as arguments but also can return them. The example below illustrates how an object can be created (within a function) and returned to another function.

Page 178: Programming In C++

class complex

{

float x;

float y;

public:

void input(float real,float imag)

{

x=real;

y=imag;

Page 179: Programming In C++

}

friend complex sum(complex,complex);

void show(complex);

};

complex sum(complex c1,complex c2)

{

complex c3; //object c3 is created

c3.x=c1.x+c2.x;

c3.y=c1.y+c2.y;

Page 180: Programming In C++

return(c3); //returns object c3

}

void complex::show(complex c)

{

cout<<c.x<<“+j”<<c.y<<“\n”;

}

int main()

{

complex A,B,C;

Page 181: Programming In C++

A.input(3.1,5.65);

B.input(2.75,1.2);

C=sum(A,B); //C=A+B

cout<<“A=“;

A.show(A);

cout<<“B=“;

B.show(B);

cout<<“C=“;

C.show(C);

Page 182: Programming In C++

return 0;

}

Page 183: Programming In C++

Chapter-6th

Page 184: Programming In C++

It is a special member function used for automatic initialization of an object. Whenever an object is created, the constructor will be executed automatically. It can be overloaded to accommodate many different forms of initialization.

Syntax Rules for Writing Constructor Functions:-

• Its name must be same as that of its class name.

• It is declared with no return type (not even void).

Page 185: Programming In C++

•It may not be static and virtual.

• It should have public or protected access within the class and only in rare circumstances it should be declared private.

Syntax:-

class username

{

private:

--------

--------

Page 186: Programming In C++

protected:

----------

---------

public:

username(); //constructor

----------

----------

};

username::username()

Page 187: Programming In C++

{

--------

----------

}

Program:-

class sample

{

int m,n;

public:

Page 188: Programming In C++

sample(int,int);

void display();

};

sample::sample(int x,int y)

{

m=x;

n=y;

}

void sample::display()

{

Page 189: Programming In C++

cout<<m<<n;

}

void main()

{

sample s(100,20);

s.display()

getch();

}

Page 190: Programming In C++

Default Constructor

It is special member function invoked automatically by C++ compiler without any arguments for initializing the objects of class.

Syntax:-

class username

{

private:

--------

--------

Page 191: Programming In C++

protected:

----------

---------

public:

username(); //default constructor

----------

----------

};

username::username() //without any arguments

Page 192: Programming In C++

{

--------

----------

}

Program:-

class student

{

private:

char name[20];

Page 193: Programming In C++

long int rollno;

char sex;

float height;

float weight;

public:

student(); //constructor

void display();

};

student::student()

Page 194: Programming In C++

{

name[0]=‘\0’;

rollno=0;

sex=‘\0’;

height=0;

weight=0;

}

void student::display()

{

Page 195: Programming In C++

cout<<“name=“<<name<<endl;

cout<<“rollno=“<<rollno<<endl;

cout<<“sex=“<<sex<<endl;

cout<<“height=“<<height<<endl;

cout<<“weight=“<<weight<<endl;

}

void main()

{

student a;

Page 196: Programming In C++

cout<<“demonstration of default constructor\n”;

a.display();

}Copy Constructor

These are always used when the compiler has to create a temporary object of a class. The copy constructors are used in the following situations:-

1. The initialization of an object by another object of the same class.

2. Return of objects as function value.

Page 197: Programming In C++

Syntax:-

classname::classname(classname &ptr)

Program:-

class code

{

int id;

public:

code()

{

Page 198: Programming In C++

}

code(int a)

{

id=a;

}

code(code &x)

{

id=x.id;

}

Page 199: Programming In C++

void display()

{

cout<<id;

}

};

void main()

{

code a(20);

code b(a);

Page 200: Programming In C++

code c=a;

a.display();

b.display();

c.display();

getch();

}

Page 201: Programming In C++

Destructor

It is a function that is automatically executed when an object is destroyed. Its primary use is to release the scope that is occupied. It may be invoked explicitly by the programmer.

Syntax Rules for writing Destructors:-

1. Its name is as that of its class expect it starts with the tilde(~).

2. It is declared with no return type.

3. It can’t be declared static.

Page 202: Programming In C++

4. It takes no arguments and therefore can’t be overloaded.

5. It should have a public access.

Syntax:-

class classname

{

various sections

classname(); //constructor

~classname(); //destructor

}

Page 203: Programming In C++

Program:-

int count=0;

class alpha

{

public:

alpha()

{

count++;

cout<<“no. of objects created<<count;

Page 204: Programming In C++

}

~alpha()

{

cout<<“no. of objects destroyed”<<count;

count--;

}

};

int main()

{

Page 205: Programming In C++

alpha a1,a2,a3,a4;

{

alpha a5;

}

{

alpha a6;

}

cout<<“reenter main”;

getch();

Page 206: Programming In C++

return 0;

}

Dynamic Initialization Of Objects

Class objects can be initialized dynamically too. That is to say, the initial value of an object may be provided 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 of data at run time depending upon the situation

Page 207: Programming In C++

Dynamic Constructors

The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus resulting in the saving of memory. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is allocated with the help of the new operator.

Page 208: Programming In C++

Chapter-7th

Page 209: Programming In C++

It is logical method of calling several functions with different arguments and data types that perform basically identical things by same name. Its main advantages are:-

1. Elimination of use of different function names for same operations.

2. Helps to understand, debug and grasp easily.

3. Easy maintenance of the code.

The function declaration and function definition are essential for each function with same

Page 210: Programming In C++

name but different arguments.

Function Overloading with Various Data Types:-

It allows to use the same function name for various data types. The function declaration, definition and function call are done with the same name but different data arguments.

The correct name will be selected by C++ compiler for comparing the types of actual parameters with formal parameters.

Function Overloading with Arguments:-

A function can also be overloaded for number of

Page 211: Programming In C++

arguments in the function call.

Scoping Rules for Function Overloading :-

The overloading mechanism is acceptable only within the same scope of the function declaration. The same function name in various classes is not said to be overloaded.The operator can also be overloaded that is they can be redefined. Its main advantages in a program is that it is much easier to read and

Page 212: Programming In C++

debug. Only predefined C++ operators can be overloaded.

Syntax:-

return_type operator operator-to-be operated(parameters)

Example:-

void operator++();

is equal to void increment();

Page 213: Programming In C++

Rules for Operator Overloading:-

1. Only predefined C++ operators can be overloaded.

2. Users can’t change any operator template i.e its use,template and precedence.

3. Overloading of an operator can’t change its natural meaning.

Page 214: Programming In C++

Unary Operator like (++,--) takes no formal arguments when overloaded by member functions. They take single arguments when overloaded by friend function.

The assignment operator is also an unary operator because it is connected only to the entity on the right side. Whenever it is overloaded in a base class, it can’t be inherited in the derived class.

Page 215: Programming In C++

Program on Overloading Unary Minus:-

class space

{

int x;

int y;

int z;

public:

void getdata(int a,int b, int c);

void display();

Page 216: Programming In C++

void operator-(); //Overload Unary minus

};

void space::getdata(int a,int b,int c)

{

x=a;

y=b;

z=c;

}

void space::display()

Page 217: Programming In C++

{

cout<<x<<“ “;

cout<<y<<“ “;

cout<<z<<“\n“;

}

void space::operator-()

{

x=-x;

y=-y;

Page 218: Programming In C++

z=-z;

}

int main()

{

space s;

s.getdata(10,-20,30);

cout<<“s:”;

-s;

cout<<“s:”;

Page 219: Programming In C++

s.display();

getch();

return 0;

}

Program on Function Overloading:-

void main()

{

int a,b;

float x;

s.display();

getch();

return 0;

}

Program on Function Overloading:-

void main()

{

int a,b;

float x;

Page 220: Programming In C++

void area(int);

void area(int ,int);

void area(int,float);

cout<<“Enter the side of square”;

cin>>a;

area(a);

cout<<“\n Enter the sides of rectangles”;

cin>>a>>b;

area(a,b);

Page 221: Programming In C++

cout<<“\n Enter the sides of triangle”;

cin>>a>>x;

area(a,x);

getch();

}

void area(int b,float h)

{

float t;

t=1/2*b*h;

Page 222: Programming In C++

cout<<“Area of Triangle=“;

cout<<t;

}

void area(int l,int b)

{

int r;

r=l*b;

cout<<“\n Area of Rectangle=“;

cout<<r;

Page 223: Programming In C++

}

void area(int f)

{

int s;

s=f*f;

cout<<“\n Area of Square=“;

cout<<s;

}

Page 224: Programming In C++

In certain situations, some variables are declared as integers but sometimes it may be required to get the result as floating point numbers. The type conversions is to convert the set of declared type to some other required type. The assignment operator can be used for type conversions. The type of data to the right of an assignment operator is automatically converted to the type of the variable on the left.

For Example:- int m;

float x=3.14159;

Page 225: Programming In C++

m=x;

convert x to an integer before its value is assigned to m. Thus the fractional part is truncated. The type conversions are automatic as long as the data types invalid are built-in-type

The compiler does not support automatic type conversions for user-defined data types. Three types of situations might arise in the data conversions between incompatible type:-

1. Conversion from basic type to class type.

2. Conversions from class type to basic type.

Page 226: Programming In C++

3. Conversions from one class type to another class type.

Program on Overloading Binary Operators:-

class complex

{

float x,y;

public:

complex(){}

complex(float real,float imag)

{

Page 227: Programming In C++

x= real;

y=imag;

}

complex operator+(complex);

void display();

};

complex complex::operator+(complex c)

{

complex temp;

Page 228: Programming In C++

temp.x=x+c.x;

temp.y=y+c.y;

return(temp);

}

void complex::display()

{

cout<<x<<“+j”<<y;

}

void main()

Page 229: Programming In C++

{

complex c1,c2,c3;

c1=complex(2.5,3.5);

c2=complex(3.6,2.1);

c3=c1+c2;

cout<<“c1=“;

c1.display();

cout<<“c2=“;

c2.display();

Page 230: Programming In C++

cout<<“c3=“;

c3.display();

getch();

}

Overloading Binary Operators using Friends class complex

{

float x;

float y;

Page 231: Programming In C++

public:

complex()

{}

complex(float real,float imag)

{

x=real;

y=imag;

}

friend complex operator+(complex,complex);

Page 232: Programming In C++

void display();

};

complex operator+(complex c1,complex c2)

{

complex c3;

c3.x=c1.x+c2.x;

c3.y=c1.y+c2.y;

return(c3);

}

Page 233: Programming In C++

void complex::display()

{

cout<<c.x<<“+j”<<c.y;

}

void main()

{

complex A,B,C;

A=complex(2.5,3.1);

B=complex(6.2,1.9);

Page 234: Programming In C++

C=A+B;

cout<<“A=“;

A.display();

B.display();

C.display();

getch();

}

Page 235: Programming In C++

Chapter-8th

Page 236: Programming In C++

Inheritance is the process by which objects of one class acquire the properties of the objects of another class. 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 old class is referred to as the Base class and the new one is called as Derived class or subclass.

Page 237: Programming In C++

A derived class with only one base class is called as Single Inheritance. One class with several base classes is called Multiple Inheritance. The process of inheriting one class by more than one class is called as Hierarchical Inheritance. The process of deriving a class from another derived class is called as Multilevel Inheritance.

Page 238: Programming In C++

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

Syntax:-

derivedclass:visibility mode baseclass

{

Members of derived class

}

Page 239: Programming In C++

The colon indicates that the derived class name is derived from the base class name. The visibility mode is either private or public. By default visibility mode is private.

For Example:-

class abc:private xyz

{

members of abc

};

class abc:public xyz

Page 240: Programming In C++

{

Members of abc;

};

When a base class is privately inherited by a derived class, public members of the base class become ‘private members’ of the derived class and therefore the public members of the base class can only be accesses by the members function of the derived class. They are inaccessible to the objects of the derived class.

When base class is publicly inherited, public members of the base class become public

Page 241: Programming In C++

members of the derived class and therefore they are accessible to the objects of the derived class.

Single Inheritance is the process of creating a number of new classes from an existing base class. The existing class is known as the direct base class and the newly created class is called as a singly derived class. Single Inheritance is the ability of a derived class to inherit the member function and variables of the existing base class.

The General Syntax is:-

class derivedclass:visibility mode baseclass

Page 242: Programming In C++

{

members of the derived class

};

Program On Single Inheritance:-

class basic

{

private:

char name[20];

int rollno;

Page 243: Programming In C++

public:

void getdata();

void display();

};

class sample:public basic

{

private:

float height;

float weight;

Page 244: Programming In C++

public:

void getdata();

void display();

};

void basic::getdata()

{

cout<<“Enter name and Rollno”;

cin>>name>>rollno;

}

Page 245: Programming In C++

void basic::display()

{

cout<<name<<rollno;

}

void sample::getdata()

{

cout<<“Enter height and weight”;

cin>>height>>weight;

}

Page 246: Programming In C++

void sample::display()

{

cout<<height<<weight;

}

void main()

{

sample s;

s.getdata();

s.display();

Page 247: Programming In C++

The process of deriving a class from another derived class is called as Multilevel Inheritance. The class A serves as a base class for the derived class B and B serves as a base class for the derived class C. The class B is known as

getch();

}

Page 248: Programming In C++

Intermediate base class since provides a link for the inheritance between A and C. The ABC chain is known as Inheritance Path.

A derived class with Multilevel Inheritance is declared as:-

class A

{

--------

};

class B:public A

Page 249: Programming In C++

{

----------

};

class C:public B

{

--------

};

Page 250: Programming In C++

Program on Multilevel Inheritance:-

class student

{

protected:

int rollno;

public:

void getnumber();

void shownumber();

};

Page 251: Programming In C++

void student::getnumber()

{

cout<<“Enter rollno”;

cin>>rollno;

}

void student::shownumber()

{

cout<<rollno;

}

Page 252: Programming In C++

class test:public student

{

protected:

float sub1;

float sub2;

public:

void getmarks();

void putmarks();

};

Page 253: Programming In C++

void test::getmarks()

{

cout<<“Enter sub1”<<endl;

cin>>sub1;

cout<<“Enter sub2”<<endl;

cin>sub2;

}

void test::putmarks()

{ cout<<sub1<<sub2;}

Page 254: Programming In C++

class result:public test

{

private:

float total;

public:

void display();

};

void result::display()

{

Page 255: Programming In C++

total=sub1+sub2;

shownumber();

putmarks();

cout<<“Total=“<<total;

}

void main()

{

result r;

r.getnumber();

Page 256: Programming In C++

r.getmarks();

r.display();

getch();

}

Page 257: Programming In C++

A class can inherit the attributes of two or more classes. This is known as Multiple Inheritance. In other words, a class with several base classes is known as Multiple Inheritance. Multiple Inheritance allows us to combine the features of several existing class as a starting point for defining a new class.

Syntax:-

class D:visibility base1,visibility base2

{

Page 258: Programming In C++

body of D

};

Program on Multiple Inheritance:-

class m

{

protected:

int m;

public:

void getm();

Page 259: Programming In C++

};

class n

{

protected:

int n;

public:

void getn();

};

class p:public m,public n

Page 260: Programming In C++

{

public:

void display();

};

void m::getm()

{

cout<<“Enter m”;

cin>>m;

}

Page 261: Programming In C++

}

void n::getn()

{

cout<<“Enter n”;

cin>>n;

}

void p::display()

{

cout<<m<<endl;

Page 262: Programming In C++

cout<<n<<endl;

cout<<m*n;

}

void main()

{

p p1;

p1.getm();

p1.getn();

p1.display();

Page 263: Programming In C++

getch();

}

The situation where all the three kinds of inheritance namely multilevel, multiple and hierarchical are invoked. The duplication of inherited members due to the multiple paths can be avoided by making the common base class as a Virtual Base Class while declaring the direct or intermediate base classes.

Page 264: Programming In C++

Grandparent

Parent 1 Parent 2

Child

Fig. Multipath Inheritance

Page 265: Programming In C++

The ‘child’ has two direct base classes ‘parent1’ and ‘parent2’ which themselves have a common base class ‘grandparent’. The ‘child’ inherits the traits of ‘grandparent’ via two separate paths. It can also inherit directly as show by the broken line. The ‘grandparent’ is sometimes referred to as indirect base class.

Inheritance by the ‘child’ as shown in fig. Might pose some problems. All the public and protected members of ‘grandparent’ are inherited into ‘child’ twice, first via ‘parent1’ and again via ‘parent2’. This means , ‘child’ would have duplicate sets of the members inherited from

Page 266: Programming In C++

‘grandparent’. This introduces ambiguity and should be avoided.

The duplication of inherited members due to these multiple paths can be avoided by making the common base class (ancestor class) as virtual base class while declaring the direct or intermediate base classes which is shown as follow:

class A //grandparent

{

------

Page 267: Programming In C++

---------

};

class B1:virtual public A //parent1

{

---------

---------

};

class B2:public virtual A //parent2

{

Page 268: Programming In C++

--------

--------

};

class C:public B1,public B2 //child

{

------- //only one copy of A

------- //will be inherited

};

When a class is made a virtual base class, C++ takes necessary care to see that only one copy of

Page 269: Programming In C++

that class is inherited, regardless of how many inheritance paths exist between the virtual base class and a derived class.

Program on Virtual Base Classes:-

class student

{

protected:

int rollno;

public:

void getnumber()

Page 270: Programming In C++

{

cout<<“Enter Rollno”;

cin>>rollno;

}

void putnumber()

{

cout<<rollno;

}

};

Page 271: Programming In C++

class test:virtual public student

{

protected:

float sub1,sub2;

public:

void getmarks()

{

cout<<“Enter sub1”;

cin>>sub1;

Page 272: Programming In C++

cout<<“Enter sub2”;

cin>>sub2;

}

void putmarks()

{

cout<<sub1<<sub2;

}

};

class sports: public virtual student

Page 273: Programming In C++

{

protected:

Float score;

public:

void getscore()

{

cout<<“enter score”;

cin>>score;

}

Page 274: Programming In C++

void putscore()

{

cout<<score;

}

};

class result:public test,public sports

{

float total;

public:

Page 275: Programming In C++

void display();

};

void result::display()

{

total=sub1+sub2;

putmarks();

putnumber();

putscore();

cout<<“total=“<<total;

Page 276: Programming In C++

}

void main()

{

result r;

r.getnumber();

r.getscore();

r.getmarks();

r.display();

getch(); }

Page 277: Programming In C++

An abstract class is one that is not used to create any objects. An abstract class is a class which consists of pure virtual functions. It is designed to act as a base class only (to be inherited by another classes). It is a design concept in program development and provides a base upon which other classes may be built.

Program on Abstract Classes:-

class base1

{

Page 278: Programming In C++

private:

int x,y;

public:

virtual void getdata();

virtual void display();

};

class base2:public base1

{

private:

Page 279: Programming In C++

int rollno;

char name[20];

public:

void getdata();

void display();

};

void base1::getdata()

{

}

Page 280: Programming In C++

void base1::display()

{

}

void base2::getdata()

{

cout<<“Enter rollno and name”;

cin>>rollno>>name;

}

void base2::display()

Page 281: Programming In C++

{

cout<<rollno<<name;

}

void main()

{

base1 *ptr;

base2 b;

ptr=&b;

(*ptr).getdata();

Page 282: Programming In C++

(*ptr).display();

getch();

}

Inheritance can be used to modify a class when it did not satisfy the requirements of a particular problem on hand. Additional members are added through inheritance to extend the capabilities of a class. Another interesting application of inheritance is to use it as a support to the hierarchical; design of a program. Many programming problems can be cast into a hierarchy where certain features of one level are shared by many others below that level.

Page 283: Programming In C++

Account

Saving account

Current account

Fixed-deposit account

Short-term

Medium-term

Long-term

Page 284: Programming In C++

There should be situations where we need to apply two or more types of inheritance to design a program. For instance, consider the case of processing the student results.

Assume that we have to give weightage for sports before finalising the results. The weightage for sports is stored in a separate class called sports. The new inheritance relationship between the various classes would be as shown in fig. below.

Page 285: Programming In C++

Student

Test

Result

Sports

Fig. Multilevel, multiple inheritance

Page 286: Programming In C++

Program on Hybrid Inheritance:-

class student

{

protected:

int rollno;

public:

void getnumber(int a)

{

rollno=a;

Page 287: Programming In C++

}

void putnumber()

{

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

}

};

class test:public student

{

protected:

Page 288: Programming In C++

float part1,part2;

public:

void getmarks(float x,float y)

{

part1=x;

part2=y;

}

void putmarks()

{

Page 289: Programming In C++

cout<<“marks obtained”<<“\n”;

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

cout<<“part1=“<<part2<<“\n”;

}

};

class sports

{

protected:

float score;

Page 290: Programming In C++

public:

void getscore(float s)

{

score=s;

}

void putscore()

{

cout<<“sports wt:”<<score<<“\n\n”;

}

Page 291: Programming In C++

};

class result:public test,public sports

{

float total;

public:

void display();

};

void result::display()

{

Page 292: Programming In C++

total=part1+part2+score;

putnumber();

putmarks();

putscore();

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

}

int main()

{

result r;

Page 293: Programming In C++

r.getnumber(1234);

r.getmarks(27.5,33.0);

r.getscore(6.0);

r.display();

getch();

return 0;

}

Page 294: Programming In C++

The constructors play an important role in initializing objects. We did not use them earlier in the derived classes for the sake of simplicity. One important thing to note here is that, as long as no base class constructor takes any arguments, the derived class need not have a constructor function. However, if any base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors.

Page 295: Programming In C++

Note:- While applying inheritance we usually create objects using the derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor. When both the derived and base classes contains constructors, the base constructor is executed first and then the constructor in the derived class is executed.

Program on Constructors in Derived Class

class alpha

{

int x;

Page 296: Programming In C++

public:

alpha(int i)

{

x=i;

cout<<“alpha initialized\n”;

}

void show_x()

{

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

Page 297: Programming In C++

}

};

class beta

{

float y;

public:

beta(float j)

{

y=j;

Page 298: Programming In C++

cout<<“beta initialized\n”;

}

void show_y()

{

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

}

};

class gamma:public beta,public alpha

{

Page 299: Programming In C++

int m,n;

public:

gamma(int a,float b,int c,int d):alpha(a),beta(b)

{

m=c;

n=d;

cout<<“gamma initialized\n”;

}

void show_mn()

Page 300: Programming In C++

{

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

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

}

};

int main()

{

gamma g(5,10.75,20,30);

cout<<“\n”;

Page 301: Programming In C++

g.show_x();

g.show_y();

g.show();

getch();

return 0;

}

Page 302: Programming In C++

Chapter-9th

Page 303: Programming In C++

Nesting of ClassesInheritance is the mechanism of deriving certain properties of one class into another. This is implemented using the concept of derived classes. C++ supports yet another way of inheriting properties of one class into another. This approach takes a view that an object can be a collection of many other objects. That is, a class can contain objects of other classes as its members as shown below:Syntax:- class XX

Page 304: Programming In C++

{

private:

int x1;

int x2;

public:

void fun1();

void fun2();

};

class YY

Page 305: Programming In C++

{

private:

int y1;

XX ox; //Object of class XX

public:

void funy();

};

Class YY has ox as one of it’s members. ox is an object of class XX. So you can have access to public members of class XX.

Page 306: Programming In C++

#include<iostream.h>

#include<conio.h>

#define PIE 3.14159

class circle

{

private:

float radius;

public:

float area()

Page 307: Programming In C++

{

float ar;

cout<<“\nRadius ?”;

cin>>radius;

ar=PIE*radius*radius;

return(ar);

}

};

class cylinder

Page 308: Programming In C++

{

private:

circle c; //c is an object of class circle

float height;

public:

float float volume()

{

float ar;

float vol;

Page 309: Programming In C++

ar=c.area(); //Member function of class circle called

cout<<“Height ?”;

cin>>height;

vol=ar*height;

return(vol);

}

};

void main()

{

Page 310: Programming In C++

cylinder c;

cout<<“Volume of the cylinder is “<<c.volume();

}

Page 311: Programming In C++

Chapter-10th

Page 312: Programming In C++

PolymorphismThe word ‘Poly’ means many and the word ‘Morphism’ means form. Therefore it means many forms. It is a process of defining a number of objects of different classes into a group and call the methods to carry out the operation of the objects using different function calls. It treats objects of related classes in a generic manner. The keyword Virtual is used to perform the polymorphism concept in C++. Polymorphism refers to the run time binding to a pointer to a method.

Page 313: Programming In C++

Early BindingWhen function is chosen in a normal way,during the compilation time, it is called as Early Binding/Static Binding/Static Linkage. The compiler determines which function is to be used based on the parameters passed and the return type of function. In Early Binding, the function call is made4 from the base class pointer to access the members of the derived class. But the function call not reaches the derived class an the function of the base class are executed. It is because, the

Page 314: Programming In C++

member function of base class and derived class are declared non-virtual and C++ complier takes only the static Binding by default. C++ supports Polymorphism through virtual method and pointers. If the member function of the base and the derived class are made Virtual, then the functions of both the classes will be executed.

Page 315: Programming In C++

Late BindingChoosing functions during execution time is called as Late Binding or Dynamic Binding. Late Binding requires some overhead but provides increased power and flexibility. The Late Binding is implemented through Virtual functions. An object of a class must be declared either as a pointer to a class or a reference to a class. The keyword “Virtual” must be followed by return type of a member function if a run time is to be bound. It is called as Dynamic Binding because the selection of the appropriate function is done dynamically at run time.

Page 316: Programming In C++

Polymorphism

Compile time

polymorphism

Run time

polymorphism

Function overloadin

g

Operator overloadin

g

Virtual functions

Page 317: Programming In C++

Pointers To Objects

Object pointers are useful in creating objects at run time. We can also use an object pointer to access the public members of an object. We can access the member functions of a class in two ways

• One by using the dot operator and the object.

• Second by using the arrow operator and the object pointer.

Page 318: Programming In C++

Program to Pointers to Objects:-

class item

{

int code;

float price;

public:

void getdata(int a,float b)

{

code=a;

Page 319: Programming In C++

price=b;

}

void show()

{

cout<<“Code: “<<code<<endl;

cout<<“Price: “<<price<<endl;

}

};

void main()

Page 320: Programming In C++

{

item x;

item *ptr;

ptr=&x;

ptr->getdata(100,25.7);

ptr->show();

getch();

}

Page 321: Programming In C++

this Pointer

A pointer is a variable that holds the memory address of another variable.”this” pointer is a variable that is used to access the address of the class itself. This unique pointer is automatically passed to a member function when it is called. The pointer “this” acts as an implicit argument to all the member function.

When a binary operator is overloaded by means of member function, we pass only one argument to the function explicitly. The other argument is implicitly passed using the pointer “this”.

Page 322: Programming In C++

Program on this pointer:-

class point

{

private:

float x;

float y;

public:

void getxy()

{

Page 323: Programming In C++

cout<<“Coordinates of the point “;

cin>>this->x>>this->y; //Accessing data members

//through pointer this

}

void showxy()

{

cout<<“\nX coordinate= “<<this->x;

cout<<“\nY coordinate= “<<this->y;

}

Page 324: Programming In C++

void where()

{

cout<<“nAddress of p is “<<this; //Displays the

//address of object

}

};

void main()

{

point p;

Page 325: Programming In C++

p.getxy();

p.showxy();

p.where();

getch();

}

Page 326: Programming In C++

Pointers To Derived Classes

Pointers To Derived Classes

We can use pointers not only to the base objects but also to the objects of derived classes. C++ allows a pointer in a base class to point to either a base class object or to any derived class object. Therefore, a single pointer variable can be made to point to objects belonging to different classes.

For example:- If B is a base class and D is derived class from B, then a pointer declared as a pointer to B can also be a pointer to D

Page 327: Programming In C++

Virtual Functions

Virtual Functions

A Virtual functions is one that does not really exist but it appears real in some parts of a program. 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.

To make a number function Virtual, the keyword Virtual is used in the method while it is declared in the class definition but not in the member function definition. The compiler gets

Page 328: Programming In C++

information from the keyword Virtual that it is virtual function and not a conventional functional declaration.

The general syntax of the Virtual function declaration is:

class user_defined_name

{

private:

statements;

public:

Page 329: Programming In C++

Virtual return_type function_name(arguments);

};

Rules for Virtual Functions:-

They are accessed by using object pointers.

A Virtual function can be a friend of another class.

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

We can’t have Virtual constructors, but can have virtual destructors.

Page 330: Programming In C++

If a Virtual function is defined in the base class, it need not be necessarily redefined in the derived class. In such cases, calls will invoke the base function.

Program on Virtual Functions:-

class base

{

public:

void display()

{

Page 331: Programming In C++

cout<<“Display base”;

}

Virtual void show()

{

cout<<“Show base”;

}

};

class derived:public base

{

Page 332: Programming In C++

public:

void display()

{

cout<<“Display derived”;

}

void show()

{

cout<<“Show derived”;

}

Page 333: Programming In C++

};

void main()

{

base b;

derived d;

base *ptr;

ptr=&b;

(*ptr).display();

(*ptr).show();

Page 334: Programming In C++

ptr=&d;

(*ptr).display();

(*ptr).show();

getch();

}

Page 335: Programming In C++

Pure Virtual FunctionsPure Virtual FunctionsA pure virtual function is a function that is only declared in the base class but have no definition relative that base class. A class containing such pure virtual function is called as abstract base class. These classes cannot be used to declare any objects of its own.

For Example:-

class base

{

Page 336: Programming In C++

int x;

float y;

public:

Virtual void getdata();

Virtual void display();

};

class derived:public base

{

int rollno;

Page 337: Programming In C++

char name[2];

public:

void getdata();

void display();

};

void base::getdata()

{

}

void base::display()

Page 338: Programming In C++

{

}

void derived::getdata()

{

cout<<“Enter name and rollno”;

cin>>name>>rollno;

}

void derived::display()

{

Page 339: Programming In C++

cout<<rollno;

cout<<name;

}

void main()

{

base *ptr;

derived d;

ptr=&d;

(*ptr).getdata();

Page 340: Programming In C++

(*ptr).display();

getch();

}

Page 341: Programming In C++

Program on Static Binding

class square

{

protected:

int x;

public:

void getdata();

void display();

Page 342: Programming In C++

int area();

};

class rectangle:public square

{

protected:

int y;

public:

void getdata();

void display();

Page 343: Programming In C++

int area();

};

void square::getdata()

{

cout<<“Enter the value of side x”\n”;

cin>>x;

};

void square::display()

{

Page 344: Programming In C++

cout<<“Value of x=y= “<<x<<endl;

cout<<“Area of the Square= “<<area();

cout<<endl;

}

int square::area()

{

int temp=x*x;

return(temp);

}

Page 345: Programming In C++

void rectangle::getdata()

{

cout<<“Enter the value of sides x and y?\n”

cin>>x>>y;

}

void rectangle::display()

{

cout<<“Value of x= “<<x<<“ and y= “;

cout<<y<<endl;

Page 346: Programming In C++

cout<<“Area of the rectangle= “<<area();

cout<<endl;

}

int rectangle::area()

{

int temp=x*y;

return(temp);

}

void main()

Page 347: Programming In C++

{ square sq;

rectangle rect;

sq *ptr;

ptr=&sq;

ptr=&rect;

ptr->getdata();

ptr->area();

ptr->display();

}

Page 348: Programming In C++

A program to illustrate the Dynamic binding of member functions of a class

class base

{

private:

int x;

float y;

public:

virtual void getdata();

Page 349: Programming In C++

virtual void display();

};

class derived:public base

{

private:

int rollno;

char name[20];

public:

void getdata();

Page 350: Programming In C++

void display();

};

void base::getdata()

{

cout<<“Enter an integer\n”;

cin>>x;

cout<<“Enter a real number\n”;

cin>>y;

}

Page 351: Programming In C++

void base::display()

{

cout<<“Entered numbers are x= “<<x<<“ and y= “<<y;

cout<<endl;

}

void derived::getdata()

{

cout<<“Enter roll number of a student ?\n”;

cin>>rollno;

Page 352: Programming In C++

cout<<“Enter name of student?\n”;

cin>>name;

}

void derived::display()

{

cout<<“roll number student’s name\n”;

cout<<roll no<<‘\t’<<name<<endl;

}

void main()

Page 353: Programming In C++

{

base *ptr;

derived d;

ptr=&d;

ptr->getdata();

ptr->display();

}

Page 354: Programming In C++

Pointers to Derived Classes

class b

{

public:

int x;

void show()

{

cout<<“x= “<<x<<endl;

};

Page 355: Programming In C++

class d:public b

{

public:

int y;

void show(){

cout<<“y =“<<y<<endl;

cout<<“x= “<<x<<endl;

}

};

Page 356: Programming In C++

void main()

{

b *ptr;

b bc;

ptr=&bc;

(*ptr).x=100;

(*ptr).show();

d dc;

ptr=&dc;

Page 357: Programming In C++

(*ptr).x=200;

(*ptr).show();

d *ptr1;

ptr1=&dc;

(*ptr1).y=300;

(*tr1).show();

getch();

}

Page 358: Programming In C++

Chapter-11th

Page 359: Programming In C++

IntroductionIntroductionEvery program takes some data as input and generates processed data as output following the familiar input-process-output cycle. It is, therefore, essential to know how to provide the input data and how to present the results in a desired form. C++ supports a rich set of I/O functions and operations to do this. Since these functions use the advanced features of C++ (such as classes, derived classes and virtual functions), we need to know a lot about them

Page 360: Programming In C++

before really implementing the C++ I/O operations.

C++ supports all of C’s rich set of I/O functions. We can use any of them in the C++ programs. But we restrained from using them due to two reasons. First, I/O methods in C++ support the concepts of OOP and secondly, I/O methods in C cannot handle the user-defined data types such as class objects.

C++ uses the concept of stream and stream classes to implement its I/O operations with the console and disk files.

Page 361: Programming In C++

C++ StreamsC++ StreamsA stream is a sequence of bytes. It acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides data to the program is called the input stream and the destination stream that receives output from the program is called the output stream. It other words, a program extracts the bytes from an input stream and inserts bytes into an output stream as illustrated in fig. below.

Page 362: Programming In C++

Input device

Output device

Program

Input stream

Output stream

Extraction from input

stream

Insertion into output

stream

Fig. Data Streams

Page 363: Programming In C++

The data in the input stream can come from the keyboard or any other storage device. Similarly, the data in the output stream can go to the screen or any other storage device. A stream acts as an interface between the program and the input/output device. Therefore, a C++ program handles data (input or output) independent of the device used.

C++ contains several pre-defined streams that are automatically opened when a program begins its execution. These include cin and cout which have been used very often in our programs. We know that cin represents the input stream

Page 364: Programming In C++

connected to the standard input device (usually the keyboard) and cout represents the output stream connected to the standard output (usually the screen).C++ Streams

Classes

The C++ I/O system contains a hierarchy of classes that are used to define various streams to deal with both the console and disk files. These classes are called stream classes. Fig below shows the hierarchy of the stream classes used for input and output operations with the console unit. These classes are declared in the header file iostream. This file should be included in all the programs that communicate with the console unit.

Page 365: Programming In C++

ios

istreamstreambu

fostream

iostream

istream_withassign

iostream_withassign

ostream_withassign

pointer

input output

Fig. Stream classes for Console I/O operations

Page 366: Programming In C++

ios is the base class for istream (input stream) and ostream (output stream) which are, in turn, base classes for iostream (input/output stream). The class ios is declared as the virtual base class so that only one copy of its members are inherited by the iostream.

The class ios provides the basic support for formatted and unformatted I/O operations. The class istream provides the facilities for formatted and unformatted input while the class ostream (through inheritance) provides the facilities for formatted output. The class iostream provides the facilities for handling both input and output streams.

Page 367: Programming In C++

UNFORMATTED I/O OPERATIONS

Overloaded Operators >> and <<

We have used the objects cin and cout (pre-defined in the iostream file) for the input and output of data of various types.

cout is used to display an object into standard device, normally the video screen. The insertion operators (the double less than <<) is used along with cout stream. The general syntax for cout is:-

cout<<variable name;

Page 368: Programming In C++

cin is used to read a number, a character or a string of characters from a standard input devices normally from keyboard.

cin>>variable name;

• put() and get() functions:- The classes istream and ostream define two member functions get() and put() respectively to handle the single character input/output operations.

• write() and getline() functions:- Function write() outputs some bytes from a character array. Syntax of statement in which object cout calls member functions write() is given below:

Page 369: Programming In C++

cout.write(str,k);

where

str=pointer to the string whose chracters are to be displayed

k=number of bytes to be displayed

getline() is used to read a character string and display the same. The syntax of the cin statement with getline() member function is given below:

cin.getline(str,max);

Page 370: Programming In C++

where

str is the pointer to the character string to be read

max is the maximum number of characters in the string.

Page 371: Programming In C++

Formatted Console I/O Operations

C++ supports a number of features that could be used for formatting the output. These features include:-

• ios class function and flags

• Manipulators

• User-defined output functions

The ios class contains a large number of member functions that would help us to format the output in a number of ways. The most

Page 372: Programming In C++

important ones among them are listed in table below:-

Function Task

width() To specify the required field size for displaying an output value

precision()

To specify the number of digits to be displayed after the decimal point of a float value

fill() To specify a character that is used to fill the unused portion of a field

Table: ios format functions

Page 373: Programming In C++

Function Task

unsetf() To clear the flags specified

setf() To specify format flags that can control the form of output display (such as left-justification and right-justification)

Manipulators are special functions that can be included in the I/O statements to alter the format parameters of a stream. Table below shows important manipulator functions that are frequently used. To access these manipulators, the file iomanip should be included in the program.

Page 374: Programming In C++

Manipulators Equivalent ios function

setw() width()

setprecision() precision()

setfill() fill()

setiosflags() setf()

resetiosflags() unsetf()

Table: Manipulators

In addition to these functions supported by the C++ library, we can create out own manipulator functions to provide any special output formats. The following sections will

Page 375: Programming In C++

provide details of how to use the pre-defined formatting functions and how to create new ones.

Defining Field width:width():-

We can use the width() function to define the width of a field necessary for the output of an item. Since, it is a member function, we have to use an object to invoke it, as shown below:

cout.width(w);

where, w is the filed width (number of columns).The output will be printed in a field of w characters wide at the right end of the field.

Page 376: Programming In C++

For example:- cout.width(5);

cout<<543<<12<<“\n”;

will produce the following output:

5 4 3 1 2

Setting Precision: precision():-

By default, the floating numbers are printed with six digits after the decimal point. However, we can specify the number of digits to be displayed after the decimal point while printing the floating-point numbers. This can be done by using the

Page 377: Programming In C++

precision() member function as follows:

cout.precision(d);

where, d is the number of digits to the right of the decimal point.

For example:-

cout.precision(3);

cout<<Sqrt(2)<<“\n”;

cout<<3.14159<,”\n”;

Result is 3.142

Page 378: Programming In C++

Filling and Padding:fill():-

We have been printing the values using much larger field widths than required by the values. The unusual positions of the field are filled with white spaces, by default. However, we can use the fill() function to fill the unused positions by any desired character. It is used in the following form:-

cout.fill(ch);

where ch represents the charcater which is used for filling the unused positions.

Page 379: Programming In C++

For example:-

cout.fill(‘*’);

cout.width(10);

cout<<5250<<“\n”;

The output would be:

* * * * * * 5 2 5 0

Page 380: Programming In C++

Character I/O with get() and put()

int main()

{

int cout=0;

char c;

cout<<“INPUT TEXT\n”;

cin.get(c);

count++;

Page 381: Programming In C++

cin.get(c);

}

cout<<“\nNumber of Characters=“<count<<“\n”;

getch();

return 0;

}

Page 382: Programming In C++

Displaying String with write() void main()

{

char str[]=“Hello”;

for(int k=1;k<=5;k++)

{

cout.write(str,k);

cout<<“\n”;

}

Page 383: Programming In C++

Reading String with getline()

getch();

}

void main()

{

in c;

char str[10];

cout<<“Enter a string :”;

cin.getline(str,10);

Page 384: Programming In C++

Specifying Field Size with width()

cout<<“The string is “<<str;

getch();

}

int main()

{

int items[2]={10,8};

int cost{2}={75,100};

cout.width(5);

Page 385: Programming In C++

cout<<“ITEMS”;

cout.width(8);

cout<<“COST”;

cout.width(15);

cout<<“TOTAL VALUE “<<“\n”;

int sum=0;

for(int i=0;i<2;i++)

{

cout.width(5);

Page 386: Programming In C++

cout<<items[i];

cout.width(8);

cout<<cost[i];

int value=items[i] * cost[i];

cout.width(15);

cout<<value<<“\n”;

cum=sum+value;

}

cout<<“\nGrand Total=“;

Page 387: Programming In C++

cout.width(2);

cout<<sum<<“\n”;

getch();

return 0;

}

Page 388: Programming In C++

Precision Setting with precision()

void main()

{

float x=34.562454;

for(int i=1;i<6;i++)

{

cout<<“Precision(“<<i<<“)”;

cout.width(10);

Page 389: Programming In C++

cout.precision(i);

cout<<x<<‘\n’;

}

getch();

}

Page 390: Programming In C++

Padding with fill() void main()

{

float x=34.562454;

for(int i=1;i<6;i++)

{

cout<<“precision(“<<i<<“)”;

cout.width(10);

Page 391: Programming In C++

cout.fill(‘*’);

cout.precision(i);

cout<<x<<‘\n’;

}

getch();

}

Page 392: Programming In C++

Managing Output with Manipulators

The header file iomanip provides a set of functions called manipulators which can be used to manipulate the output formats. They provide the same features as that of the ios member functions and flags. Some manipulators are more convenient to use than their counterparts in the class ios.

The most commonly used manipulators are shown in Table below. The table also gives their meaning and equivalents. The access these

Page 393: Programming In C++

manipulators, we must include the file iomanip in the program.

Manipulator Action

endl Inserts a new line charcater

setfill(ch) Set the fill character to ch

setprecision(p) Set the precision to p digits

setw(w) Set the field width to w

Page 394: Programming In C++

Use of Manipulators

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

void main()

{

float x=34.562454;

for(int i=1;i<6;i++)

Page 395: Programming In C++

{

cout<<“Precision(“<<i<<“)”;

cout<<setw(10);

cout<<setfill(‘*’);

cout<<setprecision(i);

cout<<x;

cout<<endl;

}

}

Page 396: Programming In C++

User-Defined ManipulatorsIn addition to the standard C++ manipulators you can define your own manipulators.

Syntax:-

ostream, &manip_name(ostream &stream)

{

statements

return(stream)

}

Page 397: Programming In C++

Example of user-defined manipulators

#include<iostream.h>

#include<iomanip.h>

#include<conio.h>

ostream &beep(ostream &stream); //Function prototype

void main()

{

int x;

Page 398: Programming In C++

do

{

cout<<endl<<“Enter the number “;

cin>>x;

if(x==0)

cout<<beep<<“Reciprocal of 0 is not defined “;

}

while(x==0);

cout<<“Reciprocal of “<<x<<“is”<<1.0/(float)x;

Page 399: Programming In C++

getch();

}

//defined manipulator beep

ostream &beep(ostream &stream)

{

cout<<‘\a’; //produce sound

cout<<‘\a’;

return(stream);

}

Page 400: Programming In C++

Chapter-12th

Page 401: Programming In C++

File Functions

Data is entered in the computer programs through the input devices. When the amount of data becomes very large, then it can be first stored in files and then can be fed to the computer programs. A file is a collection of bytes stored on some storage device.

In C++, the header file “fstream.h” contains the various file I/O functions. It also includes some classes for performing the I/O operations.

Page 402: Programming In C++

A stream means the flow of data. Different streams are used for different type of data flow. The stream that supplies data to the program is known as input stream.

It reads the data from the file and supplies it to the program. On the other hand, the stream that receives the data from the program is known as output stream. It writes the received data to the file.

Page 403: Programming In C++

Classes For File Stream Operations

The I/O system of C++ contains a set of classes that define the file handling methods. These include ifstream, ofstream and fstream. These classes are derived from fstreambase and from the corresponding iostream class as shown in fig below. These classes, designed to manage the disk files, are declared in fstream and therefore we must include this file in any program that uses files.

Page 404: Programming In C++

ios

istreamstreambu

fostrea

m

iostream

ifstream

fstream ofstream

filebuf

fstream base

iostream file

fstream file

Page 405: Programming In C++

Class Contents

filebuf Its purpose is to set the file buffers to read and write. Also contain close() and open() as members

fstreambase

Provides operations common to the file streams. Serves as a base for fstream,ifstream and ofstream class. Contains open() and close() functions.

ifstream Provides input operations. Contains open() with default input mode. Inherits the functions get(), getline(), read(), functions from istream.

Page 406: Programming In C++

ofstream

Provides output operations. Contains open() with default input mode. Inherits put() and write() functions from ostream.

fstream Provides support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the functions from istream and ostream classes through iostream.

Page 407: Programming In C++

Opening A File

To open a file in C++, the particular stream must be used first. To create an input stream, the stream must be declared of class ifstream, to create an output stream, the stream must be declared of class ofstream and to create an input stream, the stream must be declared of class fstream. The next step is to associate a file with the stream. The file can be then opened in two ways:-

Page 408: Programming In C++

(1) Opening File Using Constructors

Syntax:

ifstream input_file (“file_name”) ;

ofstream output_file (“file_name”);

The opened file is closed automatically after program completion and can also be closed explicitly as

input_file.close( );

output_file.close( );

(2) Opening File Using open( ) Function

When it is required to open and process more than one file, there is a need to create the separate stream for

Page 409: Programming In C++

each file. But if it is required to process them sequentially, then only a single stream can be used by associating the files turn by turn. This can be done by using the open( ) and close( ) functions properly.

Syntax:

ifstream file;

file.open(“file1”); ….. file.close( );

file.open(“file2”); ….. file.close( );

Page 410: Programming In C++

Sequential Input / Output Operations

1. The function get ( ): It is used to read one character or one byte from a file.

e.g. char ch;

ifstream fin;

fin.open(“filename”);

fin.get(ch);

Page 411: Programming In C++

2. The function put ( ): It is used to write one character or one byte on a file.

e.g. char ch;

ch=‘m’;

ofstream fout;

fout.open(“filename”);

fin.put(ch);

3. The function getline ( ): It is used to read multiple characters at a time from a file.

e.g. char line[100];

ifstream fin;

Page 412: Programming In C++

fin.open(“filename”);

fin.get(line);

4. The function read ( ): It is used to read the binary blocks if data from a file.

Syntax: fin.read( (char*) & buf, int sizeof (buf) );

It reads the bytes from the associated stream and puts them in the buffer pointed to by buf.

e.g. fin.read( (char*) & emp, sizeof(name) );

These functions take two arguments. The first is the address of the variable emp, and the second is the length of that variable in bytes. The address of the

Page 413: Programming In C++

variable must be cats to type char * (i.e pointer to charcater type).

5. The function write ( ): It is used to write the binary blocks of data read from buf to a file.

Syntax: fout.write( (char*) & buf, int sizeof (buf) );

It writes the bytes to the associated stream read from the buffer pointed to by buf.

e.g. fout.read( (char*) & emp, sizeof(name) );

These functions take two arguments. The first is the address of the variable emp, and the second is the length of that variable in bytes. The address of the variable must be cats to type char * (i.e pointer to charcater type).

Page 414: Programming In C++

Reading and Writing Class ObjectsThe functions read and write can also be used for reading and writing class objects. These copy the entire class object from memory in bytes without any change. The data members can be written to the disk files but not the member functions.

end-of-file marker (eof)Syntax: int eof ( );

Page 415: Programming In C++

Working With Single File

// Program on creating files with constructor function

#include<iostream.h>

#include<fstream.h>

#include<conio.h>

int main()

{

ofstream outf(“ITEM”); //Connect ITEM file to outf

Page 416: Programming In C++

cout<<“Enter item name:”;

char name[30];

cin>>name; //get name from keyboard

outf<<name<<“\n”; //write to file ITEM

cout<<“Enter item cost:”;

float cost;

cin>>cost; //get cost from keyboard

outf<<cost<<“\n”; //write to file ITEM

outf.close(); //Disconnect ITEM file from outf

Page 417: Programming In C++

ifstream inf(“ITEM”); //Connect ITEM file to inf

inf>>name; //read name from file ITEM

inf>>cost; //read cost from file ITEM

cout<<“\n”;

cout<<“Item name:”<<name<<“\n”;

cout<<“Item cost:”<<cost<<“\n”;

inf.close(); //Disconnect ITEM from inf

getch();

return 0; }

Page 418: Programming In C++

Working With Multiple Files

Program on Creating files with open() function

#include<iostream.h>

#include<fstream.h>

#include<conio.h>

int main()

{

ofstream fout; //create output stream

Page 419: Programming In C++

fout.open(“country”); //connect country to it

fout<<“USA\n”;

fout<<UK\n”;

fout<<South Korea\n”;

fout.close(); //disconnect country

fout.open(“capital”); //connect capital

fout<<“Washington\n”;

fout<<“London\n”;

fout<<“Seoul\n”;

Page 420: Programming In C++

fout.close(); //Disconnect capital

//Reading the Files

const int n=80; //size of line

char line[n];

ifstream fin; //Create input stream

fin.open(“country”); //Connect country to it

cout<<“Contents of Country file\n”;

while(fin)

{

Page 421: Programming In C++

fin.getline(line,n); //read a line

cout<<line<<endl;

}

fin.close(); //Disconnect country

fin.open(“capital); //Connect capital

cout<<“\nContents of capital file\n”;

while(fin)

{

fin.getline(line,n);

Page 422: Programming In C++

cout<<line<<endl;

}

fin.close();

getch();

return 0;

}

Page 423: Programming In C++

Errors in File OperationsThe C++ has many error handling functions

present in class ios that helps to read the category of errors.

(1) int bad ( ): It returns non-zero value if any invalid operation is performed or any unrecoverable error occurs. If it is false, the error may be recovered.

(2) int eof ( ): It returns 1 if end-of-file is encountered while file reading, otherwise it returns 0.

Page 424: Programming In C++

(3) int good ( ): It returns 1 if no error occurs, If it returns 0, then the further processing of the program is stopped.

(4) int fail ( ): It returns 1 if input or output operation is failed.

(5) clear ( ): It resets the error state to allow the further operations in the program.

Page 425: Programming In C++

Command Line ArgumentsA program can be provided some input values at the

time of execution for any need, these arguments are called as command line arguments or parameters. The main function can take two parameters namely- argc of type int and argv of type pointer to character array. These are always read as strings even if the numeric values are passed as arguments.

e.g.

void main (int argc, char *argv[])

{

int i;

Page 426: Programming In C++

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

cout<<“value= “<<argv[i];

}

Page 427: Programming In C++

File Pointers and Their Manipulations

Each file has two associated pointers known as the file pointers. One of them is called the input pointer (or get pointer) and the other is called the output pointer (or put pointer). We can use these pointers to move through the files while reading or writing. The input pointer is used for reading the contents of a given file location and the output pointer is used for writing to a given file location.

Page 428: Programming In C++

Default Actions:- When we open a file in read-only mode, the input pointer is automatically set at the beginning so that we can read the file from the start. Similarly, when we open a file in write-only mode, the existing contents are deleted and the output pointer is set at the beginning. This enables us to write to the file from the start. In case, we want to open an existing file to add more data, the file is opened in ‘append’ mode. This moves the output pointer to the end of the file (i.e. the end of the existing contents).

Page 429: Programming In C++

H E L L O W O R L D

H E L L O WO R L D

Open for reading only

Open in append mode (for writing

more data)

Open for writing only

Input pointer

Output pointer

Output pointer

“hello” file

Fig. Action on file pointers while opening a file

Page 430: Programming In C++

Functions for Manipulation of File Pointers:- All the actions on the file pointers as shown in fig. above take place automatically by default. How do we then move a file pointer to any other desired position inside the file? This is possible only if we can take control of the movement of the file pointers ourselves. The file stream classes support the following functions to manage such situations:

seekg():- Moves get pointer(input) to a specified location.

seekp():- Moves put pointer (output) to a specified location.

Page 431: Programming In C++

tellg():- Gives the current position of the get pointer.

tellp():- Gives the current position of the put pointer.

Page 432: Programming In C++

Program List

Page 433: Programming In C++

1. To find out leap year

#include<iostream.h>

#include<conio.h>

void main()

{

int year;

clrscr();

cout<<“Enter any year”;

cin>>year;

Page 434: Programming In C++

if(year%4==0)

cout<<“This is leap year”;

else

cout<<“This is not leap year”;

getch();

}

2. Prime Number

#include<iostream.h>

#include<conio.h>

Page 435: Programming In C++

#include<Math.h>

void main()

{

int num,sq,i,flag=0;

cout<<“Enter any number”;

cin>>num;

sq=sqrt(num);

for(i=2;i<=sq;i++)

{

Page 436: Programming In C++

if(num%i==0)

flag=1;

}

if(flag==1)

cout<<“Number is not a prime number”;

else

cout<<“Number is prime”;

getch();

}

Page 437: Programming In C++

3. To find the factorial of a number

#include<iostream.h>

#include<conio.h>

void main()

{

int num, fact,f;

fact=1;

clrscr();

Page 438: Programming In C++

cout<<“Enter the number\n”;

cin>>num;

for(f=1;f<=num;f++)

{

fact=fact*f;

}

cout<<“Factorial of a number is: “<<fact;

getch();

}

Page 439: Programming In C++

4. Program to find the product table of any number

#include<iostream.h>

#include<conio.h>

#include<iomanip.h>

void main()

{

int n,f;

cout<<“Enter the number :”;

cin>>n;

Page 440: Programming In C++

cout<<endl;

for(f=1;f<=10;f++)

cout<<setw(6)<<n<<“ x”<<setw(6)<<f<<“=“<<setw(6)<<n*f<<endl;

getch();

}

Page 441: Programming In C++

5. To find the length of String without functions

#include<iostream.h>

#include<conio.h>

void main()

{

char name[20];

int f;

cout<<“Enter a string”;

Page 442: Programming In C++

6. To Check Even or Odd number

cin>>name;

for(f=0;name[f]!=‘\0’;f++)

cout<<“Length of string is:”<<f<<endl;

getch();

}

#include<iostream.h>

#include<conio.h>

void main()

Page 443: Programming In C++

{

int i,j;

cout<<“Enter value of i:”;

cin>>i;

if(i%2==0)

{

cout<<“The value is even”;

}

else

Page 444: Programming In C++

7. To find the Factorial using function

{

cout<<“The value is odd”;

}

getch();

}

#include<iostream.h>

#include<conio.h>

Page 445: Programming In C++

void main()

{

int n,ft;

int fact(int);

cout<<“Enter value of n:”;

cin>>n;

ft=fact(n);

cout<<“Factorial is:”<<ft;

getch();

Page 446: Programming In C++

}

int fact(int p)

{

int i,f=1;

for(i=1;i<=p;i++)

f=f*i;

return(f);

}

Page 447: Programming In C++

8. To print the power of a number

#include<iostream.h>

#include<conio.h>

void main()

{

int f,n,p,res=1;

cout<<“Enter any number and its power”;

cin>>n>>p;

Page 448: Programming In C++

for(f=1;f<=p;f++)

{

res=res*n;

}

cout<<“Power=“<<res;

getch();

}

Page 449: Programming In C++

9. To Reverse a four digit Number

void main()

{

int num,rev,d1,d2,d3,d4;

cout<<“Enter the number”;

cin>>num;

d1=num%10;

num=num/10;

Page 450: Programming In C++

d2=num%10;

num=num/10;

d3=num%10;

num=num/10;

d4=num;

rev=d1*1000+d2*100+d3*10+d4;

cout<<“Reverse Number is=“<<rev;

getch();

}

Page 451: Programming In C++

10. To demonstrate the use of switch case structure

void main()

{

int a,b,res;

char ch;

cout<<“Enter the two numbers”;

cin>>a>>b;

cout<<“Enter the choice: a for add,\ns for

Page 452: Programming In C++

subtraction,\np for product,\nd for division,\n r for remainder”;

cin>>ch;

switch(ch)

{

case ‘a’:

res=a+b;

break;

case ‘s’:

res=a-b;

Page 453: Programming In C++

break;

case ‘p’:

res=a*b;

break;

case ‘d’:

res=a/b;

break;

case ‘r’:

res=a%b;

Page 454: Programming In C++

break;

default:

res=0;

break;

}

cout<<“Result= “<<res;

getch();

}

Page 455: Programming In C++

11. To find the sum of a 4-digit number

void main()

{

int num,sum,d1,d2,d3,d4;

cout<<“Enter a 4-digit number”;

cin>>num;

d1=num%10;

num=num/10;

Page 456: Programming In C++

d2=num%10;

num=num/10;

d3=num%10;

num=num/10;

d4=num;

sum=d1+d2+d3+d4;

cout<<“Sum is: ”<<sum;

getch();

}

Page 457: Programming In C++

12. To print the table of a number

void main()

{

int n,f,r;

cout<<“Enter the number”;

cin>>n;

for(f=1;f<=10;f++)

{

Page 458: Programming In C++

r=n*f;

cout<<n<<“ X”<<f<<“=“<<r;

cout<<endl;

}

getch();

}

Page 459: Programming In C++

13. Character Occurrence

#include<iostream.h>

#include<conio.h>

#include<string.h>

void main()

{

int i,n,count=0;

char ch,name[20];

Page 460: Programming In C++

clrscr();

cout<<“Enter the character to be counted”;

cin>>ch;

cout<<“Enter a string”;

cin>>name;

n=strlen(name);

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

count=count+1;

}

Page 461: Programming In C++

14. To find the Fibonacci series

cout<<“No. of times character in string is”<<count; getch();}

void main()

{

int i,n1,=0,n2=1,sum,n;

clrscr();

cout<<“Enter value of n”;

Page 462: Programming In C++

cin>>n;

for(i=1;i<=n;i++)

{

sum=n1+n2;

n1=n2;

n2=sum;

cout<<sum;

}

getch(); }

Page 463: Programming In C++

15. To find out HCF of 2 numbers

void main()

{

int n1,n2,r=1,hcf;

clrscr();

cout<<“Enter two numbers”;

cin>>n1>>n2;

if(n1>n2)

Page 464: Programming In C++

{

while(r!=0)

{

r=n1%n2;

n1=n2;

n2=r;

}

hcf=n1;

}

Page 465: Programming In C++

else

{

while(r!=0)

{

r=n2%n1;

n2=n1;

n1=r;

}

hcf=n2;

Page 466: Programming In C++

16. To find the Palindrome String

}

cout<<“HCF is:”<<hcf;

getch();

}

#include<string.h>

void main()

{

char name[20];

Page 467: Programming In C++

int i,j,l,flag=0;

cout<<“Enter a string”;

cin>>name;

l=strlen(name);

for(i=0,j=l-1;i<=l/2;i++,j--)

{

if(name[i]=name[j])

continue;

else

Page 468: Programming In C++

flag=1;

}

if(flag==1)

cout<<“String is not a palindrome”;

else

cout<<“String is a palindrome”;

getch();

}

Page 469: Programming In C++

17. To print numbers between two numbers

#include<math.h>

void main()

{

int num1,num2,sq,i,flag=0;

cout<<“Enter any two numbers”;

cin>>num1>>num2;

while(num1<=num2)

Page 470: Programming In C++

{

sq=sqrt(num1);

for(i=2;i<=sq;i++)

{

if(num1%i==0)

flag=1;

}

if(flag==0)

{

Page 471: Programming In C++

cout<<num1;

}

else

{

flag=0;

}

num1++

}

getch(); }

Page 472: Programming In C++

18. To reverse a string using pointers

void main()

{

char name[20],*ptr1,*ptr2,temp;

cout<<“Enter any name”;

cin>>name;

ptr1=name;

ptr2=name;

Page 473: Programming In C++

while(*ptr2!=‘\0’)

{

ptr2++;

}

ptr2--;

While(ptr1<ptr2)

{

temp=*ptr1;

*ptr1=*ptr2;

Page 474: Programming In C++

*ptr2=temp;

ptr1++;

ptr2--;

}

cout<<name;

getch();

}

Page 475: Programming In C++

19. Write a program to convert Days into Months

void main()

{

int months,days;

cout<<“Enter days\n”;

cin>>days;

months=days/30;

days=days%30;

Page 476: Programming In C++

cout<<“Months=“<<months;

cout<<“Days=“<<days;

getch();

}

20. Write a program to print a month from Year

void main()

{

int month,year;

clrscr();

Page 477: Programming In C++

cout<<“Enter month\n”;

cin>>month;

year=month/12;

cout<<“Month=“<<month;

cout<<“Year=“<<year;

getch();

}

Page 478: Programming In C++

21. To print a Day a Week

void main()

{

int days,week;

cout<<“Enter days\n”;

cin>>days;

week=days/7;

days=days%7;

Page 479: Programming In C++

22.To find the factorial of a number using recursion

cout<<“Week=“<<week;

cout<<“Days=“<<days;

getch();

}

void main()

{

int n,f;

int fact(int);

Page 480: Programming In C++

clrscr();

cout<<“Enter any number”;

cin>>n;

f=fact(n);

cout<<“The factorial of number is”<<f;

getch();

}

int fact(int x)

{

Page 481: Programming In C++

int y;

if(x==1)

return 1;

else

y=x*fact(x-1);

return y;

}

Page 482: Programming In C++

23. To find the length of string using function

#include<iostream.h>

#include<conio.h>

#include<string.h>

void main()

{

char arr[30];

int n;

Page 483: Programming In C++

clrscr();

cout<<“Enter string”;

cin>>arr;

n=strlen(arr);

cout<<“The length of string is”<<n;

getch();

}

Page 484: Programming In C++

24. Use of Ternary Operator

void main()

{

int a,b,big;

cout<<“Enter two numbers”;

cin>>a>>b;

big=(a>b)?a:b;

cout<<“Big number=“<<big;

getch();}