Top Banner
1 OBJECT ORIENTED PROGRAMMING IN C++
68
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: Notes on c++

1

OBJECT ORIENTED PROGRAMMING IN C++

Page 2: Notes on c++

2

#. INTRODUCTION TO OBJECT ORIENTED PROGRAMMING:Object oriented program development is a new programming style

having real world thinking. It is not a programming technique. So each and every programmer has his own way of thinking.

1.object2.class3.data abstracation4.data encapsulation5.inheritance6.polymorphism7.dynamic binding8.message passing

Object:An object is defined as an entity that contain data and its related

functions. The functions operate on that data. The objects may be either physical or logical.

Class:A class is defined as a collection of objects with same type of

data and functions. The functions of the class should be defined. With the help of the class we can create number of objects of type class.

Data abstraction:Abstraction is defined as a grouping of essential details and

ignoring other details. Data abstraction is defined as a named collection of data that describes a data object in a class

Data encapsulation:Encapsulation is a technique used to protect the informations in an

object from other objects. In an object data and its functions are encapsulated into a single entity. Because of this other objects and programs cannot aces the data in an object directly. This concept is called data encapsulation or data hiding

Inheritance:Inheritance is defined as sharing of attributes and functions among

classes based on a hierarchical or sequential relationshipMain class or supper classDerived class or sub class

Polymorphism:A function is said to be polymorphic, if it is applied to many

different classes with different operation.

Dynamic binding:Binding is defined as the connection between the function call and

its corresponding program code to be executed. There are 2 types of binding1. static binding2. dynamic binding

Page 3: Notes on c++

3

Static binding: the binding occurs during compilation timeDynamic binding: the binding occurs during run time. This is also called late binding.

Message passing:Message passing is a process of locating and executing a function

in response to a message. Locating means matching the given message with the list of available functions.

#. Structure in c++

Include file

Class definitionData declarationMember function definition

Main functionObject declarationBody of main function

#include<iostream.h> ……………header fileclass stu ……………class defintion{private: ………………visibility modifierint x,y; …………….data declarationpublic:void read() …………….member function {cout<<”enter the val”;cin>>x>>y;}void print(){cout<<”x=”<<x;cout<<”y=”<<y;}};void main() …………….main function{stu a; …………..data(object) declarationa.read(); ……….called member functiona.print();}

#. Control structures

A large number of functions are used that pass messages, and process the data contained in objects. A function is set up to perform a task. When the task is complex, many different algorithms can be designed to achieve the same goal. Some are simple to comprehend, while others are not.

Page 4: Notes on c++

4

1.Decision making (or) conditional statement 2.Looping statement

Decision making statement

• DMS are used to skip or to execute a group of statements based on the result of some condition.• The decision making statements are,

• (i) simple if statement• (ii) if…else statement• (iii) switch statement

Simple if statement:

• Simple if statement is used to execute or skip one statement or group of statements for a particular condition.

• The general form is

• If(test condition){

– Statement block;}Next statement;

When this statement is executed, the computer first evaluates the value of the test condition. If the value is true, statement block and next statement are executed sequentially. If the value is false, statement block is skipped and execution starts from next statement.

Example:

• #include<iostream.h>• #include<conio.h>• Void main()• {– Int mark;– Char grade;– Clrscr();– Cin>>mark>>grade;–– If(grade= =‘a’)– {– Mark=mark+10;– }–– Cout<<mark;– Getch( );}

(ii) if …else statement

Page 5: Notes on c++

5

if..else statement is used to execute one group of statements if the test condition is true or other group if the test condition is false

The gentral form

If(test condition){statement block-1;}else{statement block-2;}next statement;

when this statement is executed, the computer first evaluates the value of the test condition. If the value is true, statement block-1 is executed and the control is transferred to next statement. If the value is false, statement block-2 is executed and the control is transferred to next statement.

Ex:#include<iostream.h>#include<conio.h>void main(){int mark;clrscr();cin>>mark;

if(mark=>35)cout<<”pass";elsecout<<”fail”;getch();

}

(iii) Switch statement;Switch case is used for multiple branching. The switch statement checks the value of an expression against a list of integer or character constants. When match found, the statements associated with that constant are executed. If no match found the statements under default section are executed.

Switch(expression){case label-1:

statement block-1;break;

case label-2:statement block-2;break;

case label-3:

Page 6: Notes on c++

6

statement block-3;break;

……………………………………….………………………………………case label-n:

statement block-n;break;

default:default statement;break;

}next statement

ex:#include<iostream.h>#include<conio.h>void main(){int day;cout<<”enter the number is 1 to 7”;cin>>day;switch(day){case 1:

cout<<”Sunday”;break;

case 2:cout<<”Monday”;break;

case 3:cout<<”Tuesday”;break;

case 4:cout<<”Wednesday”;break;

case 5:cout<<”Thursday”;break;

case 6:cout<<”Friday”;break;

case 7:cout<<”Saturday”;break;

default:cout<<”Enter the current val”;break;

}}

Looping Statements:

LS are used to execute a group of statements repeatedly unit some condition is satisfied. The looping statements are

Page 7: Notes on c++

7

(i) while statement(ii) do..while statement(iii) for statement

While statement:

While(test condition){body of the loop;}next statement;

when this statement is executed, the computer first evaluates the test condition. If the value is false, the contron is transferred to next statement. if the value is true then the body of the loop is executed repeatedly until the test condition becomes false. When the test condition becomes false the control is transferred to next statement.

Ex:#include<iostream.h>#include<conio.h>void main(){int i=1;

while (i<5){cout<<”god is great”;i++;}

}

(ii) do…while statement

The general form:

do{body of the loop;}while(test condition);next statement;

when this statement is executed the body of the loop is executed first. Then the test condition is evaluated. If the value is false, the control is transferred to the next statement. If the value is true the body of the loop is executed repeatedly until the test condition becomes false. When the test condition becomes false the control is transferred to the next statement.

Ex:#include<iostream.h>

Page 8: Notes on c++

8

#include<conio.h>void main(){int i=1;

do{cout<<”god is love”;i++;}while (i<5)

}

(iv) for statememt:

for statement is used to execute a statement or a group of statements repeatedly for a known number of times. The general form is

for(initial condition; test condition; increment or decrement){body of the loop;}next statement;

when the for statement is executed the value of the control variable and tested with the test condition. If the value of the test condition is true, the body of the loop will be executed and the control is transferred to the for statement. Then the value of the control variablej is incremented or decremented. When the test condition becomes false the control is transferred to the next statement. The body of the loop is executed repeatedly as long as the test value is true

Ex:

#include<iostream.h>main(){int i,sum=0;for (i=1;i<=50;i++){sum=sum+i;}cout<<”sum=”<<sum;}

FUNCTIONS:Function is defined as a named group of statements. A function can

be divided into small modules, then each module can be represented as a function. There are two types of function in c++.1. library function2. user defined functions

Page 9: Notes on c++

9

Library function:LF are functions which are not required to be written by the

programmer. But these are available in separate files and the programmer has to include it in the appropriate places.

Ex:Cin>>,cout<<,etc.

User defined function:A user defined function or simply function has to be written by the

programmer to carry out some specific well defined task.

All c++ programs consist of one or more function. Out of this one function should be main. This function shows from where the program execution begins.

Function definition:

The general form is:

Function-type function-name ( list of argument) -> header functin{

local variable declaration;executable statement; -> statement bodyreturn(expression);

}

A function should be defined before it is used. A function has two parts1. function header2. statement body

Rules:1. Function header should not terminate with semicolon. 2. list of arguments and argument declaration are optional3. if the function has no list of arguments an empty parentheses is a must

Declaring function-type:The function type in the function header is optional. If there is

no function type in the function header the return statement by default returns a integer value.

But with the help of the option function-type in the function header we can declare the type of the value returned by the function.

Ex:1. function-name (list of arguments) - this function returns integer value2. int function-name (list of arguments) - this function returns integer value3. float function-name (list of arguments)

Page 10: Notes on c++

10

- this function returns floating point value.

Function returning nothing:If the function is not to return any value, we can declare the

function of type void, which tells c++ not to save any temporary space for a value to be sent by the function.

The general form is:Void function-name ( list of arguments)

Inline function:Inline is a keyword prefixed with the function definition. Whenever

this function is called the compiler inserts the statements in the function in the calling place.

The general form is:Inline data-type function-name(argument list)

{function body;

}

#include<iostream.h>#include<conio.h>class sample{private:int a,b;public:void getdata(){cout<<”enter the value a and b:”;cin>>a>>b;}void display();};inline void sample::display(){cout<<”The add is”<<a+b<<endl;cout<”The sub is”<<a-b<<endl;}void main(){clrscr();sample a;a.getdata();a.display();getch();}

Function Overloading:If a single function performs different operations, then that

function is called function overloading. Overloading can be implemented in two ways.

Page 11: Notes on c++

11

1. using different number of arguments2. using different type of arguments

Different Numbers:The function with same name can be defined in a same program as

given below,

1. function with no argument2. function with one argument3. function with two argument………………………………….…………………………………

according to our need we have to individually declare and define the functions. When the function is called, depending upon the number of arguments the appropriate function will be executed. This type of implementation is called overloading the function.

Different Types:The function with same name can be defined in the same program with

same number of arguments with different data types. According to our need we have to individually declare and define the functions. When the function is called, depending upon the type of the argument the appropriate function will execute. This type of implementation is called overloading the function.

Ex:#include<iostream.h>#include<conio.h>int add(int a,int b){return (a+b);}float add(int a, float b){return(a+b);}float add(float a,float b){return(a+b);}void main(){clrscr();int a,b;float c,d;cout<<”Enter the int number of a,b”;cin>>a>>b;cout<<”Enter the float number of c,d”;cin>>c>>d;cout<<”The result is”;cout<<add(a,b)<<endl;cout<<add(a,c)<<endl;cout<<add(c,d)<<endl;

Page 12: Notes on c++

12

getch();}

STRUCTURES:A structure is defined as a data type to represent different types

of data with a single name. The data items in a structure are called members of the structure.

Defining a structure:A structure definition contains a keyword struct and a user defined

structure-name

The general form is:Struct structure-name{data-type member-1;data-type member-2;……………………..……………………data-type member-n;};

Ex:Struct student{int number;int age;char sex;};

Drawbacks in structures:1. in structures we can keep only data. It is not possible to keep functions.2. data hiding is not possible in structures.

Declaration:Structure declaration means defining variables to the already

defined structure. We can define variables in two ways.1. variable definition along with the structure definition2. variable definition using structure-name.

The general form is:

(i) First ways:Struct structure-name{data-type member-1;data-type member-2;……………………..……………………data-type member-n;}variable-1, variable-2,…..variable-n;

Ex:

Page 13: Notes on c++

13

Struct student{int number;int age;char sex;}s1,s2,s3;

(ii) second ways:Struct structure-name{data-type member-1;data-type member-2;……………………..……………………data-type member-n;};structure-name variable-1, variable-2,…..variable-n;

Ex:Struct student{int number;int age;char sex;};student s1,s2,s3;

Example:#include<iostream.h>#include<conio.h>void main(){struct employee{char sex;int number;float salary;}dept1;cout<<”Give the values to the numbers\n”;cout<<”Give the sex”;cin>>dept1.sex;cout<<”Give the number”;cin>>dept1.number;cout<<”Give the salary”;cin>>dept1.salary;cout<<”Employee-details\n\n”;cout<<”Sex:”<<dept1.sex;cout<<”Number:”<<dept1.number;cout<<”Salary:”<<dept1.salary;}

CLASS:

Page 14: Notes on c++

14

A class is a userdefined datatype. It contains data and its related functions. The data and functions in a class can be defined by any one of the following visibility modifiers.

1. public2. private3. protected

public:if a data or function defined as public, it can be accessed from

outside the class.

Private:If a data or function is defined as private, it cannot be accessed

from outside the class. This concept is called data hiding.

Protected:If a data or function is defined as protected, it can be accessed

only by the classes derived from this class.

Class definition:A class definition contains a keyword class and a user defined

class-name followed by data and functions named as members of the class. The members are enclosed with in braces.

Syntax:

Class class-name{private:

variable declaration;function declaration or definition;

public:variable declaration;function declaration or definition;

protected:variable declaration;function declaration or definition;

};

Ex:#include<iostream.h>#include<conio.h>class fact{private:int I,n,sum;public:void getdata(){cout<<”Enter the value n:”;

Page 15: Notes on c++

15

cin>>n;}void display(){I=1;Sum=1;While(I<=n){sum=sum+I;I++;}cout<<”Fact is”<<sum;}};void main(){fact f;clrscr();f.getdata();f.display();getch();}

Defining Member Function:Member functions can be defined in two places:

i. Outside the class definition.ii. Inside the class definition

Outside the class definition:Member functions that are declared inside a class have to be

defined separately outside the class. Their definitions are very much like the normal functions. An important difference between a member function and a normal function is that a member function incorporates a membership ‘identity label’ in the header. This ‘label’ tells the compiler which class the function belongs to.

The general form is:Return-type class-name :: function-name (argument declaration){

function body;}

Ex:Void item :: getdata(int a, float b){number = a;cost = b;}

Inside the class definition:Another method of defining a member function is to replace the

function declaration by the actual function definition inside the class.

Ex:

Page 16: Notes on c++

16

Class item{int no;float cost;

public:void getdata(int a,float b);void putdata(void){cout<<no<<”\n”;cout<<cost<<”\n”;}};

Example:#include<iostream.h>#include<conio.h>class item{int number;float cost;public:void getdata(int a,float b);void putdata(void){cout<<”Number:”<<number<<”\n”;cout<<”Cost:”<<cost<<”\n”;}};void item :: getdata(int a, float b){number =a;cost =b;}int main( ){item x;cout<<”\n object x”<<”\n”;x.getdata(100,299.95);x.putdata( );item y;cout<<”\n object y”<<”\n”;y.getdata(200, 175.50);y.putdata();return 0;}

Array within a Class:The arrays can be used as member variables in a class. The

following class definition is valid

Class array{int a[size];

Page 17: Notes on c++

17

public:void setval(void);void display(void);};

the array variable a[] declared as a private member of the class array can be used in the member functions, like any other array variable. We can perform any operations on it. For instance, in the above class definition, the member function setval() sets the values of elements of the array a[], and display() function display the values.

Example:#include<iostream.h>#include<conio.h>class array{private:int a[10];int size;public:void read();int sum();};void array :: read(){int I;cout<<”\n enter the size:”;cin>>size;cout<<”\n enter the element one by one:”;for(I=0;I<size;I++)cin>>a[I];}int array :: sum(){int s=0,I;for(I=0;I<size;I++)s += a[I];return s;}void main(){int sum;array b;b.read();b.display();sum=b.sum();cout<<”\n sum=”<<sum;}

Array of Objects:With the help of arrays, more than one object in a class in a class

can be defined by a single name. This is called array of objects.

The general form is:

Page 18: Notes on c++

18

Class-name array-name [size];

Example:#include<iostream.h>#include<conio.h>class employee{char name[10];float age;public:void getdata(void);void putdata(void);};void employee :: getdata (void){cout<<”Enter name:”;cin>>name;cout<<”Enter age:”;cin>>age;}void employee :: putdata (void){cout<<”Name:”<<name<<”\n”;cout<<”Age:”<<age<<”\n”;}const int size=3;int main(){employee manager[size];for(int I=0;I<size;I++){cout<<”\n Details of manager”<<I+1<<”\n”;manager[I].getdata();}cout<<”\n”;for(I=0;I<size;I++){cout<<”\n manager”<<I+1<<”\n”;manager[I].putdata();}return 0;}

Friend Function:In a class, private member variables can be accessed only by the

member functions in that class. But with the help of friend function we can access the private member variables in a class. The friend function should be a non-member class

Thus friendly functions are non-member function which are used to access the private member variable in a class.

The general form is:Class class-name{

Page 19: Notes on c++

19

private:……….………public:……………….Friend return-type non-member function name(argument list);};

Rules:1. The keyword friend can be used only inside the class.2. More than one friend function can be declared in a class.3. A function can be friend to more than one class.]4. The friend function definition should not contain the scope operator.

Ex:#include<iostream.h>#include<conio.h>class sample{int a;int b;public:void setvalue(){a=25;b=40;}friend float mean(sample s);};float mean(sample s){return float(s.a+s.b)/2.0;}int main(){sample x;x.setvalue();cout<<”Mean value=”<<mean(x)<<”\n”;return 0;}

ConstructorsConstructor is a special member function. This is used to give

initial values to member variables. The constructor is invoked whenever an object of its associated class is created.

The general form is:Constructor name (parameters)

{to give initial values to member variables;

Page 20: Notes on c++

20

}

Rules:1. It should be declared as public2. No return type needed.3. When the object is declared for the class, it automatically executes the constructor and initialize the variables.

There are 3 types of constructors.(i) Constructors without parameters(ii) Constructors with paramerters(iii) Multiple constructors.

Constructors without parameters:If a constructor has no arguments then it is called constructor

without paramerter.

Ex:#include<iostream.h>#include<conio.h>class abc{int i;public:abc(){i=10;clrscr();}void print(){cout<<"\n value="<<i;}void incre(){i++;}};void main(){abc c1,c2;c1.print();c2.print();c1.incre();c1.incre();c2.incre();c1.print();c2.print();getch();}

Constructors with parameters:

Page 21: Notes on c++

21

If a constructor has arguments then it is called constsructor with parameters. The value of the arguments should be given along the object declaration.

The general form isClass-name object ( argument-value-list);

Ex:

#include<iostream.h>#include<conio.h>class item{private:int item_code;float item_price;public:item(){item_code=0;item_price=0.0;}item(int x, float y){item_code=x;item_price=y;clrscr();}void get_data(){cout<<"\n enter the code:";cin>>item_code;cout<<"\n enter the price:";cin>>item_price;}void disp_data(){cout<<"\n item code="<<item_code;cout<<"\n itemprice="<<item_price;}};void main(){item obj1;item obj2(2,10.50);obj1.disp_data();obj2.disp_data();obj1.get_data();obj1.disp_data();getch();}

Multiple constructors:

Page 22: Notes on c++

22

If a class has more than one constructor, then it is called multiple constructors. This technique is called overloading constructors.

Example:#include<iostream.h>#include<conio.h>class con{int a,b,c;public:con(int x);con(int x, int y);con(int x, int y, int z);};con :: con(int x){a = x;cout<<"Value of A is:"<<a<<endl;}con :: con(int x, int y){a = x;b = y;cout<<"Value of A is:"<<a<<endl;cout<<"Value of B is:"<<b<<endl;}con :: con(int x, int y, int z){a = x;b = y;c = z;cout<<"Value of A is:"<<a<<endl;cout<<"Value of B is:"<<b<<endl;cout<<"Value of C is:"<<c<<endl;}void main(){clrscr();cout<<"\n Creating Object With One Value"<<endl;con one(10);cout<<"\n Creating Object With Two Value"<<endl;con two(100,200);cout<<"\n Creating Object With Three Value"<<endl;con three(1000,2000,3000);getch();}Constructor with default argument:

If we give initial values to the member variables inside the argument list of constructor then it is called constructor with default arguments.

The general form is:Constructor-name ( argument-type argument-variable = value1, …);

Page 23: Notes on c++

23

Ex:

#include<iostream.h>#include<conio.h>#include<string.h>class abc{int x;float y;char z[5];public:abc(int x1=10, float y1=20.0, char z1[10]="Raam");void read(){cout<<"\n Enter x,y,z:";cin>>x>>y>>z;}void print(){cout<<"\n valuej of x="<<x;cout<<"\n valuej of y="<<y;cout<<"\n valuej of z="<<z;}};abc :: abc(int x1, float y1, char z1[]){x=x1;y=y1;strcpy(z,z1);clrscr();}void main(){abc a1;abc a2(5);abc a3(100, 12.30);abc a4(20, 16.39, "Raja");a1.print();a2.print();a3.print();a4.print();a4.read();a4.print();getch();}

DYNAMIC INITIALISATIONJOF OBJEECTS:

Dynamic initialization of objects means giving initial values to the member variables during run time. With the help of this facility, we can give different type of values to the member variables depending upon the situation.

Example:

Page 24: Notes on c++

24

#include<iostream.h>#include<conio.h>class student{int no;float weight;int age;public:student(){no=0;weight=0.0;age=0;}student(int n1,float w1,int a1);student(int n2,int w2,float a2);void print(){cout<<"\n Number="<<no;cout<<"\n weight="<<weight;cout<<"\n age="<<age;}};student :: student (int n1,float w1,int a1){no=n1;weight=w1;age=a1;}student :: student(int n2,int w2, float a2){no=n2;weight=w2;age=a2;}void main(){student s1,s2;int n,a,w1;float w,a1;clrscr();s1.print();cout<<"\n enter number, weight, age:";cin>>n>>w>>a;s1=student(n,w,a);s1.print();cout<<"\n enter thenumber,weight,age:";cin>>n>>w1>>a1;s2=student(n,w1,a1);s2.print();getch();}

Page 25: Notes on c++

25

COPY CONSTRUCTORS:Copy constructors are used to declare and initialize an object with

the values from another object. A copy constructor takes a reference to an object of the same class as itself as an argument.

Declaration:Constructor-name ( class-name &object-name ) { ………………. ………………. }

Copy constructor calling:Class-name new-obj-name ( old-obj-name );

OrClass-name new-obj-name = old-obj-name;

Example:

#include<iostream.h>#include<conio.h>class student{int no;int mark;public:student (int n1,int m1){no = n1;mark = m1;}student (student &a1){no = a1.no;mark = a1.mark;}void print(){cout<<"\n No="<<no;cout<<"\n Mark="<<mark;}};void main(){clrscr();student s1(20,400);student s2=s1;student s3(10,500);student s4(s3);s1.print();s2.print();s3.print();s4.print();getch();}

Page 26: Notes on c++

26

DYNAMIC CONSTRUCTORS:If the memory space for the constructor (memory variables) is

allocated during the constructor calling, then it is called dynamic constructor. This is done with the help of operator new. Depending on the size of the values in the variable the memory occupation of the objects varies.

Examples:

#include<iostream.h>#include<conio.h>#include<string.h>class string{char *name;int length;public:string(){length=0;name = new char [length + 1];}string (char *s){length=strlen(s);name = new char [length +1];strcpy (name,s);}void display(void){cout<<name<<"\n";}void join(string &a, string &b);};void string :: join(string &a, string &b){length = a.length + b.length;delete name;name = new char [length + 1];strcpy(name,a.name);strcat(name,b.name);};int main(){char *first = "joseph";clrscr();string name1(first), name2("louis"),name3("lagrange"),s1,s2;s1.join(name1, name2);s2.join(s1, name3);name1.display();name2.display();name3.display();s1.display();

Page 27: Notes on c++

27

s2.display();getch();return 0;}

Destructors:Destructor is a member function used to deallocate the memory space

allocated by the constructor. A destructor is a function that automatically executes when an object is destroyed. A destructor function gets executed whenever an instance of the class to which it belongs goes out of existence.

The general form is

~ destructor-name(){ ……………

……………}

~ ( tilde) -> destructor operatordestructor-name -> name of the class

The complier automatically deallocates the memory space when the program ends.

Rules:1. It won’t take any arguments2. It won’t return any value3. It cannot be declared static, const4. It should have public access in the class declaration.5. If new operator is used inside the constructor for allocating memory, delete operator should be used inside the destructor to free the memory

Example:#include<iostream.h>#include<conio.h>class baseA{public:baseA(){cout<<”base class constructor\n”;}~baseA(){cout<<”base class destructor\n”;}};class derivedD :public baseA{derivedD(){

Page 28: Notes on c++

28

cout<<”derived class constructor\n”;}~derivedD(){cout<<”derived class destructor\n”;}};void main(){derivedD obj;}

Operator Overloading:Operator Overloading is a technique used to change the predefined

operation of an operator for existing data types to a new operation for user defined data types.

All the operators can be overloaded except the operators given below.1. Conditional operator ?:2. Scope resolution operator ::3. Class member operator .*4. Size of operator sizeof5. Membership operator .

Defining operator overloading:Overloading can be defined inside the class or outside the class.

If defined inside, the declaration and definition are same. If defined outside, it should be declared inside using prototype.

The general form is:

Defining inside the class:Return-type operator symbol ( argument list ){

...............

...............}

Defining outside the class:

Declaration inside the class:Return-type operator symbol ( list of argument type);

Definition outside the classReturn-type class-name :: operator symbol ( list of argument type){

................

................}

Rules:1. Operator overloading function should be a public member function or friend function.2. Unary ++, -- can be called by prefix or post fix form.

Page 29: Notes on c++

29

Unary Operator Loading:If the symbol used in a operator overloading function is a unary

operator (-, +, ++, --, etc) then this overloading is called unary operator overloading.

Let us consider the unary minus operator. A minus operator when used as a unary, takes just one operand. We know that this operator changes the sign of an operand when applied to a basic data item.

The general form is:Return-type operator unary-symbol ( ){

...............}

Calling the function:Symbol object-name;

When this statement is executed, the symbol calls the overload function and the object value is changed depending jupon the value of the overload function.

Example:#include<iostream.h>#include<conio.h>class space{int x,y,z;public:void getdata(int a, int b, int c);void display(void);void operator-();};void space :: getdata(int a, int b, int c){x=a;y=b;z=c;}void space :: display(void){cout<<x<<" ";cout<<y<<" ";cout<<z<<"\n";}void space :: operator - (){x=-x;y=-y;z=-z;}int main(){space s;

Page 30: Notes on c++

30

clrscr();s.getdata(10,-20,30);cout<<"s:";s.display();-s;cout<<"s:";s.display();getch();return 0;}

Binary Operator Loading:If the symbol used in a operator overloading function is a binary

operator (+,-,*,/,+=,-=,etc) then this overloading is called binary operator overloading. This takes only one argument from argument list and the other from the calling object.

The general form is:Return-type operator binary-symbol (data-type1){

..............}

Calling the overloaded function:

The general form is:Object3 = object1 binary-symbol object2

When this statement is executed object1 calls the overloading symbol and passes the object2 as a argument to the overload function. Finally the calculated value will be assigned to object3 in the left hand side.

Rules:1. It requires one argument explicitly.2. The symbol is the overload function and calling must be same.

Example:#include<iostream.h>#include<conio.h>class complex{float x,y;public:complex(){}complex(float real, float img){x=real;y=img;}complex operator + (complex c);void display(void);

Page 31: Notes on c++

31

};complex complex :: operator + (complex c){complex temp;temp.x = x+c.x;temp.y = y+c.y;return(temp);}void complex :: display(void){cout<<x<<"+j"<<y<<"\n";}int main(){complex c1,c2,c3;clrscr();c1 = complex(2.5,3.5);c2 = complex(1.6,2.7);c3 = c1 + c2;cout<<"c1=";c1.display();cout<<"c2=";c2.display();cout<<endl;cout<<"c3=";c3.display();getch();return 0;}

Manipulation of Strings Using Operators:In c++ there are no operators available for string manipulation.

Butwe can overload the operators for doing the required string operation (concatination, comparision, ect.,)

Example:#include<iostream.h>#include<conio.h>#include<string.h>class string1{private:char str[40];public: void getstr() {

cout<<"\n\nEnter a string:";cin>>str;}

string1 operator + (string1 str1) { string1 str3; strcpy(str3.str,(strcat(str,str1.str))); return(str3);

Page 32: Notes on c++

32

} void printstr() { cout<<str; }};void main(){string1 a,b,c;clrscr();a.getstr();b.getstr();cout<<"\nThe first string is:";a.printstr();cout<<"\nThe 2nd string is:";b.printstr();cout<<"\n\n\n\n\nThe concatenation string is:";c = a + b;c.printstr();getch();}

Rules for Overloading Operators:1. Only existing operators can be overloaded. New operators cannot be created.2. We cannot change the basic meaning of an operator. That is, we cannot redefine the ( * ) operator to add one value to another.3. We cannot overload all operators. The operators which we cannot overload are sizeof, .*, ::, ., ?:4. Symbol used in the overload function andjin the function call must be unique.5. Binary operator overloading using member function requires one argument explicitly. But using friend function requires two arguments explicitly.6. We cannot overload all operators using friend function. They are =, ( ), [ ], ->7. The syntax rule for original operator and overloaded operator are same.

INHERITANCE:Inheritance is the process of creating new classes from the

existing classes. the new classes are called derived classes. the existing classes are called base classes.

The derived classes inherit all properties of the base classes plus its own properties. the process of inheritance does not affect the base classes.

Advantages:1. New classes can be derived by the user from the existing classes

without any modification.

Page 33: Notes on c++

33

2. It saves time and money.3. It reduces program coding time4. It increases the reliability of the program.

Syntax:class derived_class_name : mode base_class_name{ new member variable declaraction; ................................... .................................... new member function declaracion and definition ................................... ...................................};

SINGLE INHERITANCE:If a derived class is derived from a single base class, then it is

called single inheritance. single inheritance can be derived publicly or privately.

If publicly derived, the public and protected member functions of the base class becomes public and protected in the derived class. if privately derived the public and protected member functions of the base class becomes private in the derived class.

Syntax:

class base{............................};class derive 1 : mode base{............................};

Example:

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

class student{private:

int reg_no;protected:

char name[20];public:

void read(){cout<<"\n Enter the reg_no:";

Page 34: Notes on c++

34

cin>>reg_no;cout<<"\n Enter the name:";cin>>name;}

void print(){cout<<"\n Reg_no="<<reg_no;}};

class computer:public student{private:

int roll_no;public:

void read1(){read();cout<<"\n Enter the roll_no:";cin>>roll_no;}

void print1(){cout<<"\n roll_no="<<roll_no;cout<<"\n Name="<<name;}};

void main(){clrscr();computer s1;s1.read1();s1.print();s1.print1();getch();}

MULTILEVEL INHERITANCE:Multilevel inheritance is a process to derive classes in a

sequential order. A base class is treated as level 1 class. from this class we can derive a new class and is treated as level 2 class. from the level 2 class we can derive another new class and is treated as level 3 class and so on.

The lower level class inherits the higher level classes along the inheritance path.

Syntax:

class base{

Page 35: Notes on c++

35

..............

..............};class derive 1 : mode base{............................};class derive 2 : mode derive 1{......................};

Example:

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

class vehicle{protected:

char reg_no[12];

int model;public:

void read(){cout<<"\n Enter the number and model:";cin>>reg_no>>model;}void print(){cout<<"\n Reg_no="<<reg_no;cout<<"\n Model="<<model;}};

class two_wheeler : public vehicle{protected:

int no_gear;int power;

public:

void read1(){read();cout<<"\n Enter the number of gear,power:";cin>>no_gear>>power;}

void print1()

Page 36: Notes on c++

36

{print();cout<<"\n NO_gear="<<no_gear;cout<<"\n power="<<power;}};

class scotter:public two_wheeler{protected:

char manufacturer[20];char owner[20];

public:

void read2(){read1();cout<<"\n Enter the name of manufacturer and owner:";cin>>manufacturer>>owner;}

void print2(){print1();cout<<"\n Manufacturer name="<<manufacturer;cout<<"\n owner name="<<owner;}};

void main(){clrscr();scotter s1;s1.read2();s1.print2();getch();}

MULTIPLE INHERITANCE:A class derived from more than one base classes is called multiple

inheritance.Multiple inheritance allows us to combine the features of several existing classes as a starting point for defining new classes. it is like a child inheriting the physical features of one parent and the intelligence of another.

Syntax:

class base 1{................................};class base 2

Page 37: Notes on c++

37

{................................};class base 3{................................};class derived : mode base 1, mode base 2, mode base 3{................................};

Example:

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

class income{protected:

float amount;public:

void read(){cout<<"\n give the amount:";cin>>iamount;}};

class expenditure{protected:

float eamount;public:

void read1(){cout<<"\n give the amount:";cin>>eamount;}};

class n_income:public income, public expenditure{private:

float namount;public:

void print(){

Page 38: Notes on c++

38

cout<<"\n income="<<iamount;cout<<"\n expenditure="<<eamount;cout<<"\n net amount="<<namount;}

void read2(){read();read1();namount=iamount-eamount;}};

void main(){clrscr();n_income n1;n1.read2();n1.print();getch();}

HIERARCHY INHERITANCE:Hierarchy inheritance is a process to derive classes in a

hierarchical order. A base class is treated as level 1 class. From this class we can derive new classes and is treated as level 2 classes. from a level 2 class we can derive a another new classes and is treated as level 3 and so on.

The lower level classes inherits the higher level classes along inheritance path.

Syntax:

class base{............................};class derive 1 : mode base{............................};class derive 2 : mode base{......................};

Example:

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

Page 39: Notes on c++

39

class vehicle{protected:

char reg_no[10];int model;

public:void read(){cout<<"\n Enter the reg_no, and model:";cin>>reg_no>>model;}void print(){cout<<"\n Reg_no="<<reg_no;cout<<"\n Model="<<model;}

};class two_wheeler : public vehicle{protected:

int no_gear;int power;

public:void read1(){read();cout<<"\n Enter the number of gear and power:";cin>>no_gear>>power;}void print1(){print();cout<<"\n No_gear="<<no_gear;cout<<"\n Power="<<power;}

};class scooter : public two_wheeler{protected:

char manufacturer[20];char owner[20];

public:

void read2(){read1();cout<<"\n Enter the name of manufacturer and owner:";cin>>manufacturer>>owner;}void print2(){print1();cout<<"\n Manufacturer:"<<manufacturer;

Page 40: Notes on c++

40

cout<<"\n Owner:"<<owner;}

};class four_wheeler : public vehicle{protected:

char fuel[20];int no_cylinder;

public:void read3(){read();cout<<"\n give the type of fuel and no.of cylinder:";cin>>fuel>>no_cylinder;}void print3(){print();cout<<"\n fuel type="<<fuel;cout<<"\n number of cylinder="<<no_cylinder;}

};class car : public four_wheeler{protected:

char name[20];char owner[10];

public:void read4(){read3();cout<<"\n enter the name and owner:";cin>>name>>owner;}void print4(){print3();cout<<"\n name="<<name;cout<<"\n owner="<<owner;}

};void main(){clrscr();scooter s1;car c1;s1.read2();s1.print2();c1.read4();c1.print4();getch();}

HIBRID INHERITANCE:

Page 41: Notes on c++

41

An inheritance class derived from a base class and an inheritance class or two inheritance classes is called hybrid inheritance.

- Ex: (Multilevel, Multiple Inheritance):

Example:

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

class vehicle{protected:

char reg_no[10];int model;

public:void read(){cout<<"\n Enter the reg_no and model:";cin>>reg_no>>model;}

};class four_wheeler : public vehicle{protected:

int no_cylinder;public:

void read1(){read();cout<<"\n enter the no. of cylinder:";cin>>no_cylinder;}

};class car : public four_wheeler{protected:

char name[10];char owner[20];int no_seats;float price1;

public:void read2(){read1();cout<<"\n enter the name, owner, no_seats, prince1:";cin>>name>>owner>>no_seats>>price1;}

};class ac{protected:

float capacity;char make[20];

Page 42: Notes on c++

42

float price2;public:

void read3(){cout<<"\n Enter capacity, make, price2:";cin>>capacity>>make>>price2;}

};class ac_car:public car, public ac{protected:

float total_price;float fitting_charge;

public:ac_car(){fitting_charge = 1000.0;}void read4(){read2();read3();total_price=price1+price2;}void print(){cout<<"\n Reg_no="<<reg_no;cout<<"\n Model="<<model;cout<<"\n No_cylinder="<<no_cylinder;cout<<"\n Name="<<name;cout<<"\n Owner="<<owner;cout<<"\n NO_Seats="<<no_seats;cout<<"\n Total_price="<<total_price+fitting_charge;}

};void main(){clrscr();ac_car a1;a1.read4();a1.print();getch();}

AMBIGUITY:Whenever a data member and member function are defined with the

same name in both the base and the derived classes, these names must be without ambiguity. The scope resolution operator ( :: ) may be used to refer to any base member explicitly. This allows access to a name that has been redefined in the derived class.

Two base classes have functions with the same name, and also the same function name in derived class, we have ambiguity. The compiler which function is accessed from where.

Page 43: Notes on c++

43

Example:

#include<iostream.h>#include<conio.h>class a{public:void display(){cout<<"\n I am in class A";}};class b{public:void display(){cout<<"\n I am in class B";}};class c:public a,public b{};void main(){clrscr();c obj;obj.display(); // ambiguity compilation errorobj.a::display();obj.b::display();getch();}

VIRTUAL BASE CLASS

When a class is made a virtual base class, c++ takes necessary care to see that only one copy of that class is inherited, regardless of how many inheritance paths exist between the virtual base class and a derived class

The 'child' has two direct base classes 'parent1' and 'parent2' which themselvces have a common base clas 'grandparent'. the 'child' inherits the gtraits of 'grandparent' via two separate paths. it can also inherit directly as shown by the broken line. the 'grandparent' is sometimes referred to as indirect base class.

Syntax:

class a{..........................};class b1 : virtual public a{

Page 44: Notes on c++

44

...............

...............};class b2 : virtual public a{............................};class c : public b1, public b2{.........................};

Example:

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

class vehicle{protected:

char reg_no[10];int model;

public:void read(){cout<<"\n Enter the REG_NO and MODEL:\n";cin>>reg_no>>model;}

};class road_vehicle : virtual public vehicle{protected:

int no_wheel;char fuel[10];

public:void read1(){cout<<"\n Enter the WHEELS and FUEL:\n";cin>>no_wheel>>fuel;}

};class water_vehicle : virtual public vehicle{protected:

int no_leaf;char fuel1[10];

public:void read2(){cout<<"\n Enter the NO_OF LEAF and FUEL:\n";cin>>no_leaf>>fuel1;}

Page 45: Notes on c++

45

};class road_water_vehicle : public road_vehicle,public water_vehicle{private:

int status;public:

void read3(){read();read1();read2();cout<<"\n Enter the Status: 1 or Another No:\n";cin>>status;}void print(){if(status==1){cout<<"\nReg_no="<<reg_no;cout<<"\nModel="<<model;cout<<"\nNo_wheel="<<no_wheel;cout<<"\nFuel="<<fuel;}else{cout<<"\nReg_no="<<reg_no;cout<<"\nModel="<<model;cout<<"\nNo_leaf="<<no_leaf;cout<<"\nFuel="<<fuel1;}

}};void main(){clrscr();road_water_vehicle rw;rw.read3();rw.print();getch();}

ABSTRACT CLASSES:An abstract class is one that is not used to create objects. An

abstract class is designed only to act as a base class (to be inherited by other classes). It is a design concept in program development and provides a base upon which other classes may be built.

A class is said to be abstrat class if it satisfies the following conditions.1. It should act as base class.2. It should not be used to create any objects.

Example:

Page 46: Notes on c++

46

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

class student{private:

int reg_no;protected:

char name[20];public:

void read(){cout<<"\n Enter the reg_no:";cin>>reg_no;cout<<"\n Enter the name:";cin>>name;}

void print(){cout<<"\n Reg_no="<<reg_no;}};

class computer:public student{private:

int roll_no;public:

void read1(){read();cout<<"\n Enter the roll_no:";cin>>roll_no;}

void print1(){cout<<"\n roll_no="<<roll_no;cout<<"\n Name="<<name;}};

void main(){clrscr();computer s1;s1.read1();s1.print();s1.print1();getch();}

Page 47: Notes on c++

47

NESTING OF CLASSES ( CONTAINER CLASSES )

class student{private:char school_name[20];char degree[20];public:void get_student_detail(){cout<<"Enter the name of school:";cin>>school_name;cout<<"Enter the higher degree earned \n";cout<<"(Bachelor, Master, ph.d, Highschool ect.,)";cin>>degree;}void print_detail(){cout<<"\n School or University:"<<school_name;cout<<"\n Higher degree earned:"<<degree;}};class employee{private:char name[80];int empno;public:void get_emp_detail(){cout<<"Enter Emoloyee No:";cin>>empno;cout<<"Enter employee name:";cin>>name;}void print_emp_detail(){cout<<"\n Employee number:"<<empno<<"\n";cout<<"\n Employee name:"<<name<<"\n";}};class administrative{private:char designation[80];float basic;employee emp;student stud;public:void get_data(){emp.get_emp_detail();cout<<"Enter designation:";

Page 48: Notes on c++

48

cin>>designation;cout<<"Enter the basic pay:";cin>>basic;stud.get_student_detail();}void print(){emp.print_emp_detail();cout<<"Designation:"<<designation<<"\n";cout<<"Basic pay:"<<basic<<"\n";stud.print_detail();}};void main(){administrative a;clrscr();cout<<"Enter the details of administrative staff\n";a.get_data();cout<<"The detailsj of the staff are:\n";a.print();getch();}

Pointer Expressions:A Pointer is a variable data type and hence the general rule to

assign its value to the pointer is same as that of any other variable data type.

For example:int x;int *ptr;ptr = &x;

The memory address of variable " X " is assigned to the pointer variable ptr1.

Example:

#include<iostream.h>#include<conio.h>void main ( ){int x;int *ptr;x = 10;ptr = &x;clrscr ( );cout<<"X="<<x<<"and ptr ="<<ptr<<endl;cout<<"X="<<x<<"and *ptr ="<<*ptr<<endl;getch ( );}

The Output:

Page 49: Notes on c++

49

X = 10 and ptr = 0x24ccfff4X = 10 and *ptr = 10

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 objects. The objects for a class can be accessed using pointers.

The general form for declaring object using pointer is:

Class classneme{

member variable declaration;member function declaration and definition;

};

classname object1;classname *ptr;ptr = & object1;

Ex:

#include<iostream.h>#include<conio.h>class computer{private:int ram;int speed;char name[10];public:void read(){cout<<"\n Enter the value of ram, spesed, name:"<<endl;cin>>ram>>speed>>name;}void print(){cout<<"\n Name="<<name;cout<<"\n Speed="<<speed<<"MHz";cout<<"\n Ram="<<ram<<"MB";}};void main(){computer c1;computer *ptr;ptr = &c1;clrscr();ptr->read();ptr->print();getch();}

Page 50: Notes on c++

50

VIRTUAL FUNCTION:Virtual function is a function which does not really exist. But

appears real to some parts of a program.It is used to call a particular function from derived class having

more than one function with same name. For this the base class member function must be declared as virtual.

This is an application of polymorphism. Here, we use the pointer to base class to refer all the derived objects.

Example:#include<iostream.h>#include<conio.h>class base{public:void display(){cout<<"\n Display Base";}virtual void show(){cout<<"\n Show Base";}};class derived : public base{public:void display(){cout<<"\n Display Derived";}void show(){cout<<"\n Show Derived";}};int main(){base b;derived d;base *bptr;cout<<"bptr points to base \n";bptr = &b;bptr -> display();bptr -> show();cout<<"\n\n bptr points to Derived \n";bptr = &d;bptr -> display();bptr -> show();return 0;}

Unformatted I/O( i ) Input Operation:-

Page 51: Notes on c++

51

The input operations are carried out using the following Member function.

1. Overload Operator >>This operator is overloaded in the istream class and is used to

give input from keyboard to program. The general form isCin>>var1>>var2>>........>>varn;

Ex:int number;float average;cin>>number>>average;

2. get ( )This function is used to input a single character to the program.

This is a member function of istream class and is accessed with the help of the object cin. There are two types of get ( ) function.a. get ( char )b. get ( void )

get ( char ):This function is used to assign the input character to its

argument. The general form is

Syntax: cin.get ( variable-name );

Ex: char opt;cin.get ( opt );

when cin.get ( opt ) is executed the given character input is assigned to the variable opt.

get ( void ):This function is used to assign the input character to the variable

on the left hand side. The general form is

Syntax: variable-name = cin.get ( )Ex: char opt;

opt = cin.get ( )when opt = cin.get ( ) is executed the given character is assigned to the variable opt on the left hand side.

3. getline ( )This function is used to input a line of text to the program. This

is a member function of istream class and is accessed with the help of the object cin. The general form is

Syntax: cin.getline ( variable-name,size);Ex: char name[10];

cin.getline(name,10);When cin.getline ( name, 10 ) is executed the given line of text size 9 is assigned to the variable name. One place is used for the terminator ‘\0’. The reading of the line ends when the new line character ( \n ) is reached or the size is reached.

Page 52: Notes on c++

52

( ii ) Output Operation:-The output operation is carried out using the following member

functions.

1. Overloaded Operator <<This operator is overloaded in the ostream class and is used to

output data from program to VDU. The general formiscout<<outputlist;

Ex: int x = 10;Float y = x + 20;cout<<x<<y;

2. put ( )This function is used to output a single character from program to

the VDU. This is a member function of ostream class and is accessed with the help of the object cout. The general form is

cout.put ( variable-name );

Ex: char d = ‘a’;…………..cout.put ( d );

When cout.put ( d ) is executed this displays the character a on the VDU.

cout.put ( 35 );This display the character # on the VDU. Because 35 is the ASCII value of hash (#)

3. write ( )This function is used to output a line of textfrom program to VDU.

This is a member function of ostream class and is accessed with the help of the object cout. The general form is

cout.write ( variable-name, size );

Ex: char name [10];cout.write (name,10);

When cout.write(name,10) is executed the characters stored in the variable name is displayed on the VDU. If the size is grater than the length of the line then it displays beyond bounds of line.

Formatted console I/O: In c++ number of functions are available to format the output.

These functions are the member functions of the class ios. They are1. width ( )2. precision ( )3. fill ( )4. setf ( )5. unsetf ( )

1. width ( ):This function is used to specify the width of the data to be

printed. Since it is a member function, this is accessed with the help of the object cout. The general form is

Page 53: Notes on c++

53

Syntax: cout.width ( size );

2 5Ex1: int a = 25; output:

cout.width ( 4 );cout<<a;

Ex2: int a = 400; output:4 0 0

cout.width ( 2 );cout<<a;

Rules:1. The value printed is right justified.2. If the size of the width is less than the actual data width c++ automatically increases the size depending on the data size.3. The include file iostream.h should be included in the program.

2. precision ( )This function is used to specify the number of digits to be

displayed after the decimal point. Since it is a member function this is accessed with the help of the object cout. The general form is

Syntax: cout.precision ( size );

Ex: float a = 4522.72597601;cout<<a;

4 5 2 2 . 7 2 5 9cout.precision ( 4 ); output:cout<<a;

4 5 2 2 . 7 2 5 9 7 6cout.precision ( 7 ); output:cout<<a;

Rules:1. Default precision size is 6.2. default precision can be changed by giving our own precision size.3. it won’t print the trailing zeros.3. fill ( )

This function is used to print the given character in the unfilled position of the number printed. Since it is a member function, this is accessed with the help of the object cout. This is called filling and padding.

Syntax: cout.fill ( arg );

Ex: int a = 750;* * * 7 5 0

cout.fill (‘*’); output:cout.width(6);

Rules:

Page 54: Notes on c++

54

1. Default fill is blank space.2. If one character is used in the fill, it remains until we change it.

4. setf ( ) – Using bit field groupThis function is used to set the flags and bit field group of the

class ios. This is used to change the existing output settings. This is a member function of class ios.

Syntax: cout.setf(var1,var2);

Ex: int a = -46;cout.fill(‘@’); output:

- @ @ @ 4 6cout.setf ( ios::internal, ios::adjustifield );

cout.width ( 6 );cout<<a;

Rules:1. It is used to print the text left justified.2. Numeric is printed right justified.

The tables given below lists the possible flag setting and its group.

Format required Flag (arg1) Bit-field (arg2)

Left-justified output ios :: left ios :: adjustfieldRight-justified output ios :: right ios :: adjustfieldPadding after sign ios :: internal ios :: adjustfieldOr base indicator(like +##20)

Scientific notation ios :: scientific ios :: floatfieldFixed point notation ios :: fixed ios :: floatfield

Decimal base ios :: dec ios :: basefieldOctal base ios :: oct ios :: basefieldHexadecimal base ios :: hex ios :: basefieldsetf ( ) – Without bit field group

This function is used to set the flags in the class ios. This is used to display the trailing zeros and the plus sign in the output. This is a member function of a class ios.

Syntax: cout.setf(flag);

Ex: float a = -100.000;float b = 12.72;cout.setf(ios :: showpoint);cout.setf(ios :: showpos);

cout.width(10); output- 1 0 0 . 0 0 0cout<<endl<<a;

cout.width(10); output

Page 55: Notes on c++

55

+ 1 2 . 7 2cout<<endl<<b;

5. unsetf ( )This function is used to clear the flags already set to their

default settings.

Flag Meaningios :: showpoint To show trailing decimal point and zeroesios :: showpos To print + before positive numbers.

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. They are1. setw()2. setprecision()3. setfill()4. flush5. endl

1. setw()This function is used to specify the width of data to be printed.

This is equivalent to width().

Syntax: setw(size);

Ex: int a = 123; output:1 2 3cout<<setw(5)<<a;

2. setprecision()This function is used to specify the number jof places after the

decimal point. This is equivalent to precision().Syntax: setprecision(size);

Ex: float y = 9873.273;cout<<setw(10); output:

9 8 7 3 . 2 7cout<<setprecision(2)<<y;

3. setfill()This function is used to print the given character jin the unfilled

position jof the number printed. This is equivalent to fill().

Syntax: setfill(int var1); or setfill(char var2);

Ex: int a = 567;cout<<setfill(‘*’); output:

* * 5 6 7cout<<setw(5)<<a;

Page 56: Notes on c++

56

int a = 567;cout<<setfill(35); output:

# # 5 6 7cout<<setw(5)<<a;

Where 35 is the ASCII value of the character #.

4. flushThis function is used to clear the output buffer.

Syntax: flush;

Ex: int a = 20;cout<<a;cout<<flush;

5. endlThis function brings the control to the new line and flushes the

buffer while printing the data.

Syntax: endl;

Ex: int a = 10;float b = 20.35;cout<<a<<endl<<b;

Function for manipulation of File Pointers:Normally the file pointer position is changed automatically during

file processing. But we can control the file pointer movement with the help of the following member function. 1. seekg() – Moves get pointer (input) to a specified location.2. seekp() – Moves put pointer (output) to a specified location.3. tellg() – Gives the current position of the get pointer.4. tellp() – Gives the current position of the put pointer.

The table given below shows the possible flags available:

Flag Meaningios :: beg sets the pointer at the beginning of the fileios :: cur sets the pointer in the current positionios :: end sets the pointer at the end of the file

1. seekg():This function is used to move the input pointer to the position

specified. The general form is

Syntax: filename-object . seekg (pos,flag);Ex: fstream student;

student . open (“student.dat”, ios :: in);student . seekg (-20, ios :: end);

When the last statement is executed, output file pointer is set at the end of the file and moves 20 byte backward from the end.

2. seekp():

Page 57: Notes on c++

57

This function is used to move the output pointer to the position specified. The general form is

Syntax: filename-object . seekp (pos, flag);Ex: fstream student;

student . open (“student.dat”, ios :: out);student . seekg (-20, ios :: end);

When the last statement is executed, output file pointer is set at the end of the file and moves 20 byte backward from the end.

3. tellg()This function returns the byte number of the current position of

the input file pointer. The general form is

Syntax: int var1 = filename-object . tellg();Ex: fstream student;

student . open (“student . dat”, ios :: in);student . seekg(20);int p = student . tellg();

When the above statements are executed 20 is assigned to p.

4. tellp()This function returns the byte number of the current position of

the output pointer. The general form is

Syntax: int var1 = filename-object . tellp();Ex: fstream student;

student . open (“student . dat”, ios :: out);student . seekg(20);int p = student . tellg();

When the above statements are executed 20 is assigned to p.