You are on page 1of 35

Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

1. Class and Objects:


1.1 Class:

A class is the collection of objects of the similar type.

Class is a user defined data type. It is a way to bind the data and its associated functions
together. When we define a class, we are creating a new “Abstract data type” that can be treated
like any other Build – in data type. A class declaration is similar to the Structure declaration.

Syntax:

class class-name

private:

Variable declaration;

Function declaration;

public:

Variable declaration;

Function declaration;

protected:

Variable declaration;

Function declaration;

};

 Classes are created using the keyword “class”.


 The body of the class is enclosed within “braces” and terminated by a “semicolon”.
 The variable declared inside the class are known as “Data Member”.
 The function declared inside the class are known as “Member Functions”.
 The class members are grouped under the three visibility labels or access specifier
namely:
1. private
2. public
3. protected

JS Page 1
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Private:

Private allows function or data to be accessible only by other members of the same class.

Public:

Public allows function or data to be accessible from anywhere of your program.

Protected:

It is same as private. and this will be needed when class are inherited.

Example:

class employee
{
private:
int eno;
char name[80];
public:
void getdata( );
void putdata( );
};

1.2 Object:

Anything in the world is called as an “object”. Objects are instance of the class.
Once a class has been declared, we can create variables of that type by using the class name.
These variables are called as “objects”.

Syntax:
class-name object1,object2…………….object n;
Eg:
employee e1,e2;

1.3 Accessing the Class Members:

Objects are used to access the members of the class.


Syntax:
Object-name . function –name(Arguments);
Object-name . data-member;
Eg:
e1 . getdata( );

JS Page 2
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Example:

#include<iostream.h>
class sample
{
private:
int age;
public:
void getdata( )
{
cin>>age;
}
void putdata( )
{
cout<<”age is:”<<age;
}
};
void main ( )
{
sample s;
s.getdata( );
s.putdata( );
}

1.4 Defining member function:

The functions declared inside the class are known as “Member function”. These functions
are defined in two ways:

 Outside the class definition


 Inside the class definition.

Outside the class definition:

If a function is declared in a class and defined separately outside of the class is known as
outside the class definition. The important different between a member function and normal
function is “identity label” in the header. (i.e) class-name ::

JS Page 3
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Syntax:

return-type class-name :: function-name(arguments)


{
function body
}

Eg:
void sample :: putdata( )
{
cout<<”age is:”<<age;
}

Inside the class definition:

If the function is declared and defined within a class is called as inside the class
definition. it same as the normal function definition.

Example:

class employee
{
int number;
public:
void get( );
void putdata( ) // inside class definition
{
cout<<”number is”<<number;
}
};

1.5 Private Member Function:

Normally we place the all the data items in the private section and all the function in the
public. Some situation may require certain function to be hidden from outside calls.
For that reason member functions are placed in the private section. A private member
function can only be called by another function that is a member of a class. Even an object can’t
invoke a private function using the dot operator.

JS Page 4
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Example:

class sample
{
private:
int m;
void read(void); //private member function
public:
void update(void);
};

if s1 is an object of sample class, then

s1.read( ); // won’t work: objects can’t access private member function

void sample :: update(void)


{
read( ); //calling function: it will work ;no object needed.
}

1.6 Array of Object:

If we declare objects in the type of array is called as array of objects.

Example:

#include<iostream.h>
class employee
{
char name[30];
public:
void getdata( );;
void putdata( );
};
void employee :: getdata(void) output
{ enter name: xxxx
cout<<”enter name:”;
cin>>name; enter name: yyyy
}
void employee :: putdata( void) enter name: zzzz
{
cout<<”name is:”<<name;
}

JS Page 5
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

const int size=3; xxxx


int main( )
{ yyyy
employee m[size];
for(int i=0;i<size;i++)
{ zzzz
m[i].getdata( );
}
for(int i=0;i<size;i++)
{
m[i].putdatadata( );
}
}

1.7: Array within a class:

It is possible to use class data members as array type. This array type member is accessed
by an object. This process is called as “object of array”.

Example:

class sample
{
public:
int a[30]; //object of array
void getdata()
{
for(int i=1;i<=30;i++)
cin>>a[i];
}
};
void main( )
{
sample s;
for(int i=1;i<=20;i++)
cout<<s.a[i];
}

The data members can be accessed through the object s.sample[1] , s.sample[2] and so on.

JS Page 6
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

1.8. Friend Function:

Friend function is the special function. The class grants these functions a special privilege to
access private member of class. To declare a friend function it should begin with the word
“friend”
.
Syntax:

friend return-type function-name(argument-list)


{
//statements;
}

Friend function can be friend with more than one class. But not inherited. It can’t use either
scope resolution operator :: or class name friend functions are called like normal function.

Example:

#include <iostream.h>
class sample
{
int a,b;
public:
void getdata( )
{
cin>>a;
cin>>b;
}
friend int add(sample s); // friend function declaration
};
int add(sample s) //friend function defined like normal function.
{
int sum;
sum=s.a+s.b;
return(sum);
}
void main( )
{
sample x;
x.getdata( );
int m=add(x); //friend function called like a normal function.
cout<<”addition:”<<m;
}

JS Page 7
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

In this example , the add( ) function is not a member of class “sample” . but still it access the
private member of the class “sample”. Because function add( ) is a friend for the class “sample”.

Advantage of friend function:

 It is non-member function of class, but it can access the private data of the class.
 It can be invoked like a normal function without help of any object.
 It can be declared either in the public or private part of a class. Without affecting its
meaning.
 It is useful with operating overloading.

Disadvantage of friend function:

 Having friend function actually is violating of information hiding principle of OOPs.


 Since the friend function can access the private member of the class.

Advantages of member function:

 Member function can access the private data of the class. A non-member function can’t
do so.
 A member function can call another member function without using the dot operator.
 Several different classes can use the same function name.

1.9 Static Data Members Of Class:

 Static variables are normally used to maintain common to the entire class. They are
initialized only once. They retain their values between calls.

Features:

 It is initialized to zero when the first object is created. No other initialization is permitted.
 It is only visible within class, but its life time is the entire class.
 Type and scope of each static member variable must be defined outside the class.

Accessing the static data members:

There are two ways to access the static data members:

1. class-name :: static-datamember-name;
2. Object-name . static-datamember-name;

JS Page 8
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Example:

#include<iostream.h>
#include<conio.h>
class test1
{
public:
static int sv;
void display();
};
void test1::display( )
{
sv++;
cout<<"\n after increment:"<<sv;
}
int test1 :: sv; \\ initialized to 0
void main()
{
test1 t,t1,t2;
clrscr( );
t.display( );
t1.display( );
t2.display( );
getch( );
}
Output
After increment:1
After increment:2
After increment:3

1.10 Static member function:


• A member function that is declared as static has the following properties:
• A static function can have access to only other static member declared in the same class.

JS Page 9
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

• They cant be virtual


• They cant be declared as const.
• A static member function can be called using the class name.

• Accessing static member function:


• classname :: function-name(arguments);

Example:

#include<iostream.h>
class test
{
public:
static int sv;
static void display( )
{
cout<<“sv is :<<sv<<“\t”;
}
};
int test :: sv; // initializing to 0
void main( )
{
test ts1;
ts1.sv=20; //accessing static data member
test :: display( ); //accessing static member function
}

Output:
sv: 20

2. Constructor and Destructor:

2.1 Constructor:

The constructor is a special member function whose task is to initialize the objects of its
class. The constructor is invoked whenever an object of its associated class is created.

JS Page 10
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

2.1.1 Characteristic of Constructor function:

 Class name and function name is same.


 It should be declare in the public section.
 It can be invoked automatically when the objects are created.
 Do not have return type, so can’t return any value.
 Cannot virtual function.
 Can have default arguments and it can be overloaded.
 Cannot refer to their address.
 Cannot be inherited, through a derived class can call the base constructor.

Syntax:
class-name( Arguments)
{
//Constructor body
}

Example:

class student
{
private:
int rollno;
public:
student( ) //constructor
{
rollno=0;
}
};

2.1.2 Types of Constructor:

1. Default Constructor.
2. Parameterized constructor
3. Copy constructor.

1. Default Constructor:

A constructor with no arguments is called as Default Constructor or no argument constructor.

Example:

class student
{
private:

JS Page 11
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

int rollno; output:


public:
student( ) Initial values provided by constructor
{
rollno=0; Roll number is: 0
}
void printdata( )
{
cout<<”\n Rollno is:”<< rollno;
}
};
void main( )
{
student s1;
cout<<”\n initial value provided by constructor “;
s1.printdata( );
}

2. Parameterized constructor:

A constructor contains single or multiple arguments are called as parameterized constructor.

Example:

class student
{
private:
int rollno;
public:
student(int r ) //parameterized constructor
{
rollno=r;
}
void printdata( )
{ output:
cout<<”\n Rollno is:”<< rollno; Roll number is: 1000
}
};
void main( )
{
student s1=student(1000);

JS Page 12
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

s1.printdata( );
}
3. Copy constructor:

This is used to declare and initialize an object from other object. It takes a
reference to an object of the same class as an argument.

Syntax:
class-name(class-name &reference-object)
{
//Body of the constructor
}

Example:

class integer
{
private:
int m;
public:
integer(int x) //parameterized constructor
{
m=x;
}
integer(integer &i)
{
m=i.m;
}
void show()
{
cout<<”\t m is:”<<m;
}
};
void main( )
{
integer i1(10); //calling parameterized constructor
integer i2(i1); //calling copy constructor.
i2.show( );
)
Output: m is :10

JS Page 13
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

2.2 Destructor:
A destructor is used to destroy the objects that have been created by a constructor. Like
constructor , the destructor is a member function whose name is same as the class name but it
prefixed by ~ tilde) symbol.
It takes no arguments no return type even void.

Syntax: ~class-name( ); Eg: ~student( );

Example :

#include<iostream.h>
int i=0;
class dest
{
public:
dest( )
{
i++;
cout<<”\n object:”<<i<<”created”;
}
~dest( )
{
cout<<”\n object”<<i<<”destroyed”;
i - -;
}
};
void main( )
{
dest s1 s2,s3,s4;
}

Output:

Object:1 created Object:4 destroyed


Object:2 created Object:3 destroyed
Object:3 created Object:2 destroyed
Object:4 created Object:1 destroyed

2.3 Difference between constructor and destructor:

JS Page 14
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Constructor Destructor
1. It is used to construct the object It is used to destroy the object
2. It can be called automatically when an It is called when an object goes out of scope.
object comes into an existence
3. The constructor function is called every The destructor function is called every time the
time an object is created. program exits a block.
4. It is the function invoked first before It is the function called at last.
calling any function.
5. It takes any number of arguments It takes no argument.
6. It can be overloaded It cannot be overloaded
7. A class can have multiple constructor Only one destructor function for a class is
possible
8. Constructor name and class name Destructor name and class name should be the
should be the same. Eg: student ( ) same but it is prefixed by ~ Eg:~student
9. It cannot be declared as virtual function It can be a virtual function.
10. It behaves like a new operator. It behaves like a delete operator.

2.4 similarities between constructor and destructor:

Constructor Destructor
1. It is a special member function It is also a special member function
2. Unlike member function, it can be Unlike member function, it can be called
called automatically, without using automatically, without using object and dot or
object and dot or arrow operator. arrow operator.
3. It has no return type even void It also has no return type even void

3. Inheritance:

The mechanism of deriving a new class from an old one is called Inheritance or
(derivation) (i.e) derived class reusing the properties of the existing class.
1. The old class is referred to as the BASE CLASS
2. The new class is referred to as the DERIVED CLASS or subclass.

3.1 Defining derived class:


Syntax:

class derived –class name : visibility-mode base-class name


{
//members of derived class.
};

JS Page 15
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

 The colon indicates that the “derived class name” is derived from the “base class
name”.
 Visibility mode is optional. it may be either private or public.
 The default visibility mode is private.
Example:

class A
{
public:
void show( );
};
class B : public A
{
int x;
public:
void show1 ( );
};
 When a base class is privately inherited by a derived class “public members” of the base
class become “private members” of the derived class.
 When a base class is publicly inherited by a derived class. “Public members” of the base
class become “public members” of the derived class.
 In both cases , the private members are no t inherited . Therefore the private member of a
base class will never become the members of its derived class.

3.2 Types of inheritance:

1. Single inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance.

1. Single Inheritance:

One derived class is derived from only one base class is called as “single inheritance”.
Base class
A

B Derived class
The properties of base class A is inherited by Derived class B.

JS Page 16
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Example:

#include<iostream.h>
class base1
{
public:
void show( )
{
cout<<”\n base class function is executed:”;
}
};
class derived : public base1
{
public:
void show1( )
{
show( );
cout<<”\n derived class function is executed:”;
}
};
void main( ) output:
{
derived x; base class function is executed
clrscr( ); derived class function is executed.
x.show1( );
}

2. Multiple Inheritance:

A class can inherit properties from two or more class is known as Multiple Inheritance. It is like
a child inheriting the physical feature of parent.

A B C Base classes

D Derived class

Syntax:

class derived-class name : visibility mode base-class name1 , visibility mode base-class name2...
JS Page 17
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

{
//Body of derived class
};

Example:
#include<iostream.h>
class base1
{
public:
void show1( )
` {
cout<<”Base class 1”;
` }
};
class base2
{
public:
void show2( )
{
cout<<”Base class 2”;
}
};
class derived : public base1, public base2
{
public:
void show3( )
{
show1( );
show2( );
cout<<”Derived class 1”;
} output:
};
void main( ) Base class 1
{ Base class 2
derived d; Derived class 1
d.show3( );
}
3. Multilevel Inheritance:

JS Page 18
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

A class can be derived from another derived class is called as Multilevel inheritance. (i.e) the
class A servers as a Base class for the Derived class B. and Class B is servers as a Base class for
the Derived class C. now the class B is known as intermediate base class.

Base class A Grand father

B
Inter mediate class Father

C
Derived class child

Example:

#include<iostream.h>
class base1
{
public:
void display1( )
{
cout<<”base class 1”;
}
};
class derived1 : public base1
{
public:
void display2( )
{
display1( );
cout<<”derived and base class”;
}
};
class derived2 : public derived1
{
public:
void display3( )
{
display2( );
cout<<”derived class”;
}

JS Page 19
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

}; output:
void main( )
{ base class1
derived2 d; derived and base class
d.display3( ); derived class
}

4. Hierarchical Inheritance:

The properties of one base class are inherited by more than one derived class is known as
“hierarchical Inheritance”.

A Base class

B C D
Derived classes

Example:

#include<iostream.h>
class base1
{
public:
void show1( )
{
cout<<”base class”;
}
};
class derived1 : public base1
{
public:
void show2( )
{
show1( );
cout<<”derived class 1”;
}
};
class derived2 : public base1
{
public:
void show3( )

JS Page 20
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

{
show1( );
cout<<”derived class 2”;
}
};
void main( ) output:
{
derived1 d1; base class1
derived2 d2; derived class1
d1.show2( ); base class1
d2.show3( ); derived class 2
}

5. Hybrid Inheritance:

If a program is designed by using two or more types of inheritance, it is called as “Hybrid


Inheritance”.
A B

Example:

#include<iostream.h>
class base1
{
public:
void output1( )
{
cout<<”class base1”;
}
};
class base2
{
public:
void output2( )
{
JS Page 21
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

cout<<”class base2”;
}
};
class derived1 : public base1 ,public base2
{
public:
void output3( )
{
output1( );
output2( );
cout<<”class derived1”;
}
};
class derived2 : public derived1
{
public:
void output4( )
{
output3( );
cout<<”class derived2”;
} output:
};
void main( ) class base1
{ class base2
derived2 x; class derived1
x.output4( ); class derived2

}
4.Operator Overloading:
C++ has the ability to provide a special meaning to an operator is known as “Operator
Overloading”.
Defining Operator Overloading:
Syntax:
return-type class-name :: operator op(argument)
{
Function body
}
Where “return type” is the type of value returned by the specified operator.
“op” is the operator being overload.

JS Page 22
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

4.1 condition for processing of operator Overloading:

 Create a class that defines the data type that is to be used in the overloading operator.
 Declare the operator function operator op( ) in the public part of the function.
 Define the operator function to implement the required operations.

4.2 Two types of operator overloading:

1. Overloading Unary Operator.


2. Overloading Binary Operator.

Overloading Unary Operator:

The unary operator has only one operand. Unary minus (-), increment(++) , decrement
(--) etc. these operators are used to do the operator overloading process.

Example:

#inclue<iostream.h>
class unary
{
int a,b;
public:
void getdata(int x,int y);
void display( void);
void operator++( );
};
void unary :: getdata(int x, int y)
{
a=x;
b=y;
}
void unary :: display(void)
{cout<<”a=”<<a;
cout<<”b=”<<b;
}
void unary :: operator++( )
{
a=++a;
b=++b;
}
JS Page 23
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

void main( )
{
unary u; output:
u.getdata(10,20);
++u; a=11
u.display( ); b=21
getch( );
}

Overloading Binary Operator:

The same mechanism can also be used in binary operator overloading. If we want to add
two user defined data type. Statements like,

C=sum(A,B); //functional notation

But using operator overloading That functional notation can be replaced by a natural
looking expression. (i.e) statement like.

C=A+B;

The following example clearly shows the binary operator overloading:


Example:

#include<iostream.h>
class complex
{
float real ,img;
public:
complex( ) { }
complex(float r , float i)
{
real=r;
img=i;
}
complex operator+(complex); //operator function declaration.
void putdata( )
{
cout<<real<<”+i”<<img;
}
};
JS Page 24
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

complex complex :: operator+(complex c2) // operator function definition


{
complex temp;
temp.real = real + c2.real;
temp.img = img + c2.img;
return temp;
}
void main( ) output:
{
complex c1(10.2,2.1), c2(2.2,3.4),c3; 12.4 +i5.5
c3=c1+c2;
c3.putdata( );
}
Operators that cannot be overloaded:

 The dot operator.


 Scope resolution operator ( : : )
 Size operator ( sizeof )
 Conditional operator ( ? : )

5.Type Conversion:

The compiler support automatic type conversion between basic data types (i.e) the type
of the variable to the right of an assignment operator is automatically converted to the type of the
variable on the left.

Example:

int m;
float x = 3.14159;
m=x;
in the above example , the conversion between float to int (i.e basic data type) is done by
compiler without any error. The compiler doesn’t support automatic type conversion for the user
defined data types. It can also be done using operator overloading.
Three types of data conversion between incompatible types:

1. Conversion from basic type to class type.


2. Conversion from class type to basic type.
3. Conversion from class type to another class type.

JS Page 25
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

1. Conversion from basic type to class type:

The conversion from the basic type to class type is easy to accomplish using
constructor.

Example:
// Basic Type to Class Type

#include<iostream.h>
class sample
{
int a,b;
public:
sample( ) { }
sample(int x)
{
a=x;
b=x;
}
void display( )
{
cout<<”a=”<<a<<”b=”<<b;
}
};
void main( ) output:
{
sample s; a=5 b=5
int n=5;
s=n ; or s=sample(n); //convert basic type to class type.
s.display( );
}

2. Conversion from class type to basic type:

Conversions from class type to basic type the constructor function do not support
this operation. C++ introduced the new function called “conversion function”.

JS Page 26
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Syntax:
Operator type-name( )
{
Function body
}
Condition for conversion function:
 It must be a class member
 It must not specify return type.
 It must not have any argument.

Example:

#include<iostream.h>
class sample
{
int a,b;
public:
sample(int x, int y)
{
a=x;
b=y;
}
operator int( )
{
int s;
s=a+b;
return(s);
}
};
void main( ) output:
{
sample obj(70,70); sum=140
int k;
k=obj; or k=int(obj); //convert class type to basic type.
cout<<”sum=”<<k; }

3. Conversion from class type to another class type:

Conversion from class to another class type is easy to accomplish by using either
constructor or conversion function.

JS Page 27
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Example:

#include<iostream.h>
class abc
{
public:
int a;
abc( )
{
a=-1;
cout<<”a=”<<a;
}
};
class xyz
{
public:
int x;
xyz( )
{
x= -2;
cout<<”x=”<<x;
}
xyz(abc k)
{
x=k.a;
cout<<”x=”<<x;
} output:
};
void main( ) a= -1 , x= -2 , x= -1
{
abc a1;
xyz x1;
x1=a1; or x1=xyz(a1); //convert class “abc” to “xyz”.
}

6.pointer:

Def: a pointer is a variable that hold the address of the another variable is called “pointer
variable”.

JS Page 28
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

Pointer to object (or) object pointer:

A pointer can point to object created by a class is called as “pointer to objects”.


The arrow operator -> is used to access the member of the class.

Example:

Item x;
Item *ptr;

Where, item is a class


X is an object
*ptr is an object pointer of type item.
We can create the object pointer using “new” operator because of , allocate the memory at the
time of creation.

Example:

Item *ptr = new item( );


Object pointer “ptr” has created.

Example program:

#include<iostream.h>
class item
{
int a,b;
public:
void display( );
};
void main( )
{
item x;
item *ptr;
ptr -> display( );
…………
………….
}

Explain “this” pointer:

JS Page 29
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

“this” is a pointer that points to the object for which this function was called. In other
hand , a this pointer refers to an object that currently invokes a member function.

Example:

The function call a.show( ) will set the pointer this to the address of the object “a”.

Example program:

person &person :: greater(person &x)


{
if(x.age>age)
return x;
else
retrn *this;

}
The function will return the object(argument object) if the age of person B is greater than that of
A . Otherwise it will return the object A (invoking object) using the pointer “this”.

7. Polymorphism:

Polymorphism means one name having multiple forms. It has two types:
1. Compile time polymorphism
2. Runtime polymorphism

Compile time polymorphism:

The overloaded member functions are selected for invoking by matching arguments both
type and number. This information is known to the compiler at the time of compilation time and
therefore the compiler is able to select the appropriate function for a particular call at the compile
time itself. This called compile time polymorphism.
Eg: function overloading , operator overloading

Example:

void add(int,float);
void add(float,int);
void add(int);

JS Page 30
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

In the above example statements are selected at compile time. (i.e) selected depending upon
arguments and number.

Runtime polymorphism:

Let us consider a situation where the prototype is same in both the base class and derived class.

Example:

class a
{
int x;
public:
void show( ); //base class show
};
class b :: public a
{
int y;
public:
void show( ); //derived class show
};

How do we use the member function show( ) to print the values of objects of both class A and
class B? the compiler doesn’t know what to do and defers the decision. It would be nice if
appropriate number could be select while the program is running . this is known as “Runtime
Polymorphism”.

[Note: C++ supports a mechanism known as virtual function to achieve runtime polymorphism]

8. Virtual function:

A virtual function is a member function. (i.e) declared within a base class and redefined
by a derived class”. We can create a virtual function by using the keyword “virtual”.

JS Page 31
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

When we use the same function in both the base and derived class, the function in base
class is declared as virtual to avoid confusion between two of this function.

8.1 Rules for virtual function:

 The virtual function must be members of some class.


 The virtual function must be preceded by “virtual “keyword in the base class.
 The function in the derived class must have the same name has of the virtual function
defined in the same class.
 The function in the derived class need not be preceded by virtual keyword. if it is
preceded by the virtual keyword , it makes no difference.
 If a function with same name is not define in the derived class then original base class
function is invoke.
 They are accessed by using object pointer.
 A virtual function in a base class must be defined, even though it may not be used.

Example:

#include<iostream.h>
class base
{
public:
virtual void show ( )
{
cout<<” this is base function”;
}
};
class derived : public base
{
public:
void show( )
{
cout<<”this is derived function”;
}
};
void main( ) output:
{
base *ptr, b; this base function
derived d;
ptr=&b; this derived function
ptr->show( ); //access base show( )
JS Page 32
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

ptr=&d;
ptr->show( ); //access derived show( )
}

9. Managing Console I/O Operations:

9.1 C++ Stream:


A 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. cin
represents the input stream connected to the standard input devices.
And the destination stream receives output from the program is called the output stream.
cout represents the output stream connected to the standard output devices.
input stream 1

Input extracting from input


stream
device

program

Output insertion into output


stream
device
output stream 1

Fig: Data Stream.


9.2 C++ Stream classes:
The C++ I/O system contains a hierarchy of classes that are used to define various
streams. These classes are called Stream Classes. These classes are declared in the header file
iostream.

9.3 Unformatted I/O operations:

1.Overloaded operators >> and <<


The >> operator is overloaded in the istream class and << is overloaded in the ostream
class.
Eg: Cin>> code; cout<<”code is”<<code;

2.Put( ) and get( ) functions:


The classes istream and ostream define two member function get( ) and put( )
respectively to handle the single character input and output operations.

JS Page 33
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

get( ) – the function get( ) , a member of istream class, can be used to accept character
Eg: cin.get( c);

put( )- the function put( ), a member of ostream class, can be used to output a line of text,
character by character. Eg: cout.put( c);

3. getline( ) and write( ) functions:


We can read and display a line of text more efficiently using the line oriented I/O
functions. getline( ) and write( ).

getline( ) – this function reads a whole line of text that ends with a new line character. This
function invoked by using the object cin as follows: Eg: cin.getline(line, size);

write( ) – this function displays an entire line. Eg: cout.write(line, size);

9.4 Formatted Console I/O operations:


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

width( ) - which is used to define the width of the field Eg: cout.width(w);

precision( ) – to specify the number of digits to be displayed after the decimal point.
Eg: cout.precision(d);

fill( ) – it is used to fill the unused positions by any desired character. Eg: cout.fill(ch);

JS Page 34
Unit - 2 [PROGRAMMING IN C++ AND DATA STRUCTURES]

JS Page 35

You might also like