Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Rayalaseema University, Kurnool: Paper-IV: Programming in C and C++ Programming in C: Unit - I

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 76

RAYALASEEMA UNIVERSITY, KURNOOL

II Year U.G. Degree syllabus from the academic year 2013-2014


Second Year B.A./B.Com./B.Sc. (Computer Applications)
Paper-IV : Programming in C and C++
Theory : 3 hrs/week (Max. Marks: 100) Practicals : 2 hrs/week (Max. Marks: 50)
Programming in C :

Unit – I
Overview of C – Constants, Variables, and Data Types – Managing Input and Output
Operations – Operators and Expressions – Decision Making and Branching Statements –
Decision Making and Looping Statements.

Unit – II
Arrays – Character Arrays and Strings – Functions: Built-in and user-defined Functions –
Structures and Unions – Pointers – Pointer Arithmetic – Pointers to Arrays.

Unit – III
Pointers to Functions and Structures – Linked Lists – Files – Input/Output Operations on
Files – Sequential and Random Access to Files – Command Line Arguments.
Programming in C++ :

Unit – IV
Principles of Object-Oriented Programming – Tokens, Expressions and Control Structures –
Functions in C++ – Classes and Objects.

Unit – V
Constructors and Destructors – Operator Overloading and Type Conversions – Inheritance,
Types of Inheritance – Extending Classes – Pointers, Virtual Functions and Polymorphism.

Reference books:
1. Computing Fundamentals and C Programming : E.Balagurusamy, TMH
2. Object-Oriented programming with C++, 4th Edition : E.Balagurusamy, TMH

Lab Work: (50 Marks)


C Programs --- minimum 12 programs
C++ Programs --- minimum 8 programs

QUESTION PAPER SETTING


PART–A : Eight Short Note Questions (5 from Units-I, II & III and 3 from Units-IV & V)
PART–B : Eight Long Questions (5 from Units-I, II & III and 3 from Units-IV & V)
C++
LANGUAGE
C++ LANGUAGE

C++ is an object oriented programming language.


1.It was initially named as c with classes.
2 It was developed by B.Jarne Stroustrup in 1980’s at AT & T Bell Labs. Stroustrup an admiral of simula
67 and a strong supporter of c wanted to continue the best of both languages and create a more powerful
language that could support object oriented programing feature and still retain the power of C. The result
was C++ or CPP which is an extension of C with the major addition of class construct features of simula
67.
Since the class was a major addition to the original C language the stroustrup called the new
language as “C with classes” . Later in 1983 the name was changed to C++ or CPP.

1.PRINCIPLES OF OBJECT ORIENTED PROGRAMMING.


Differences between structured programming language and object oriented programing?
Structure program Oops

Structured Programming Object Oriented Programming


1.Structured Programming is designed
1. Object Oriented Programming is
which focuses on process/ logical structure
designed which focuses on data.
and then data required for that process.
2.Structured programming follows top- 2.Object oriented programming follows
down approach. bottom-up approach.
3.Structured Programming is also known as 3.Object Oriented Programming
Modular Programming and a subset of supports inheritance, encapsulation,
procedural programming language. abstraction, polymorphism, etc.
4.In Object Oriented Programming,
4.In Structured Programming, Programs are
Programs are divided into small entities
divided into small self contained functions.
called objects.
5. Object Oriented Programming is
5. Structured Programming is less secure as
more secure as having data hiding
there is no way of data hiding.
feature.
6.Structured Programming can solve 6.Object Oriented Programming can
moderately complex programs. solve any complex programs.
7.Object Oriented Programming
7.Structured Programming provides less
provides more reusability, less function
reusability, more function dependency.
dependency.

Basis concepts of Oops:-


The general concepts of Oops are
1.Objects 5.Polymorphism
2.Classes 6.Inheritance
3.Data Abstraction 7.Dynamic binding
4.Encapsulation 8.Message passing.
1.Objects:- Objects are the runtime entities in an object oriented system . They may represent a person, a
place, a bank account.
When a program is executed, the objects interact by sending messages to one and other. For example,
if “Customer” and “account” are two objects in a program then the customer object may send a message
to the account object requesting for the bank balance .Each object without having to know the details of
each other’s data or code. It is sufficient to know the type of message accepted and the type of response
returned by the objects. The notation for an object is as follows:

Object: Student

DATA
Name
Date-of-Birth
Marks
………………
………………
FUNCTIONS
Total
Average
Display
………………
……………...

2.Classes:We just mentioned that objects contain data and code to manipulate that data. The entire set of
data and code of an object can be made a user defined data type with the help of a class. In fact, objects
are variables of the type class. Once a class has been defined, we can create any number of objects
belonging to that class. Each object is associated with the data of type class with which they are created.
A class is thus a collection of objects of similar type. For example, mango, apple and orange are members
of the class fruit. Classes are user defined data types and behave like the built – in – types of a
programming language. The syntax used to create an object is no different than the syntax used to create
an integer object in C. If fruit has been defined as a class, then the statement
Fruit mango;
Will create an object mango belonging to the class fruit

3.Data Abstraction and Encapsulation:


The wrapping up of data and functions into a single unit (called class) is known as encapsulation.
Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world,
and only those functions which are wrapped in the class can access it. These functions provide the
interface between the object’s data and the program. This insulation of the data from direct access by the
program is called data hiding or information hiding.
Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all
the essential properties of the objects that are to be created. The attributes are sometimes called data
members because they hold information. The functions that operate on these data are sometimes called
methods or member functions.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types
(DAT).
4.Inheritance:
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. It supports the concept of hierarchical classification. For example, the bird ‘robin’ is a part
of the class ‘flying bird’ which is again a part of the class ‘bird’. The principle behind this sort of division
is that each derived class shares common characteristics with the class from which it is derived as
illustrated in Fig.1.8
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. The new class will have the combined features of both the classes.
Bird
Attributes
Feathers
Lay eggs

Flying birds Non Flying birds

Attributes Attributes
…………………….. ……………………..
………………….... …………………....
…………………….. ……………………..

Robin Swallow Penguin Kiwi

Attributes Attributes Attributes Attributes


…………………….. …………………….. …………………… ……………………..
………………….... ………………….... ………………….... …………………....
…………………….. …………………….. …………………….. ……………………..
Note that each sub-class defines only those features that are unique to it. Without the use of classification,
each class would have to explicitly include all of its features.

5.Polymorphism:
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability
to take more than one form. An operation may exhibit different behaviors in different instances. The
behavior 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 process of making an operator to exhibit
different behaviors in different instances is known as operator over loading.
Figure illustrates that a single function name can be used to handle different number and different
types of arguments. This is something similar to a particular word having several different meanings
depending on the context. Using a single function name to perform different types of tasks is known as
function over loading.

Shape
Draw ( )

Circle object Box object Triangle object


Draw (circle) Draw ( box) Draw (triangle)

6.Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding (also known as late binding) means that the code associated with a given procedure call
is not known until the time of the call at run – time. It is associated with polymorphism and inheritance
7.Message passing:
An object – oriented program consists of a set of objects that communicate with each other. The
process of programming in an object – oriented language, therefore, involves the following basic steps:
1. Creating classes that define objects and their behavior
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way
as people pass messages to one another. The concept of message passing makes it easier to talk about
building systems that directly model or simulate their real-world counterparts.
Example:

Structure of C++ Program

Header File Declaration Section

1. Header files used in the program are listed here.


2. Header File provides Prototype declaration for different library functions.
3. We can also include user define header file.
4. Basically all preprocessor directives are written in this section.

Global Declaration Section

Global Variables are declared here.

1. Global Declaration may include -

1. Declaring Structure
2. Declaring Class
3. Declaring Variable
.
Classes declaration section:- In C++ all the data items and functions which are used in the program can
be included in the class declaration section. The class contains set of data items are known as instance
variables.
“Class” Starts with a key word “Class’
Ex: class student
{
data;
fun();
};
Syntax:
class name
{
Private:
data members;
member functions;
Public:
data members;
member functions
};
Functions definition section:- We can write code for all functions which are declared in different
classes. The code is independent for each function depending on the task perform by that function. These
functions are called member functions.
The code under these functions is invoked them then function call make with the help of object
in the main program.
Main function selection (or) program:- Every C++ program have one “main( )”. The compiler begins
the execution of a program from main( ) only. For accessing the instances variables the objects are
created in the main program.

Header files and their Purpose:-


Header files Purpose
1.< iostream.h>: It contains function prototype for the standard input and output functions.
2.< ctype.h>: Contains functions prototypes for functions that text characters for certain properties.
Function prototype can be used to convert lower case letters to upper case letters and vice-versa.
3.< float.h>: Contains floating point size limits of the system.
4.< math.h >: contains function prototype and math library functions.
5.< stdio.h >: standard input output function.
6.< stdlib.h >: contains function prototype for conversion of numbers to text, text to numbers and various
other utility functions.
7.< string.h >: contains function prototype from c-style strung processing function.
8.< time.h >: contains functions prototype and types for manipulating time and date.
9.< iomanip.h>: contains functions prototype for the manipulation that enable for mating of streams of
data.
10. < fsream.h >: contains function prototypes for functions that performs input from files on disc and
output to files on disc.

CONTROL STATEMENTS:
Control statements are used to control the flow of a program according to the condition or requirement in
a loop. These are mainly two types of control statements.
1. Branching.
2. Looping.
1.Branching statements:- It is also called as decision making statement. The various branching statements
are.
i)If—statement:- The If statement is the powerful decision making statement which can handle a
single condition or a group of statements. When only one condition occurs in a statement, “Simple-if”
statement is used.
Syntax for simple if:-
if (condition)
{
statement-1;
statement-2;
}
Statement-x;
If the expression is true then the statements immediately following “if” are executed. Otherwise
control passes through the next statement.
W.A.P to find if you are in teenage usage “simple if”.
# include < stdio.h >
main( )
{
int age;
cout<< “Enter your age” << end l;
cin>> age;
if ((age>=13) && (age<=19))
{
Cout<< “ u r in teenage” <<age;
}
}
ii) if else
If block sometimes is followed with the optional else block. When the if condition becomes false then
else block gets executed.
Syntax:-
if(condition)
{
Statement-1;
Statement-2;
-------------
-------------
}
else
{
statement-3;
}
Ex:-Wap to find if the student is passed or not using if else
#include <iostream.h>
int main ()
{
// declare local variable
int marks = 30;

// check the boolean condition


if( marks > 40 )
{
// if condition is true
cout << "You are pass !!" << endl;
}
else
{
// if condition is false
cout << "You are fail !!" << endl;
}

return 0;
}

iii) Else if ladder

:- A multi way decision can be written by using if-else constraints in the else part.
If expression is true whole chain is terminated. Only if expression 1 is false the chain will
continue, at any stage. If an expression is true, the remaining chain will be terminated.
Syntax:-
if(boolean_expression 1)
{
// When expression 1 is true
}
else if( boolean_expression 2)
{
// When expression 2 is true
}
else if( boolean_expression 3)
{
// When expression 3 is true
}
else
{
// When none of expression is true
}

Example: Wap to find the class of the student usinf else if ladder
#include <iostream>

int main ()
{
// declare local variable
int marks = 55;

// check the boolean condition


if( marks >= 80 )
{
// if 1st condition is true
cout << "U are 1st class !!" << endl;
}
else if( marks >= 60 && marks < 80)
{
// if 2nd condition is false
cout << "U are 2nd class !!" << endl;
}
else if( marks >= 40 && marks < 60)
{
// if 3rd condition is false
cout << "U are 3rd class !!" << endl;
}
else
{
// none of condition is true
cout << "U are fail !!" << endl;
}

return 0;
}

iv)Switch case statement:- The switch case statement is the better option than the else if statement. It is
a multi-decision maker. In the switch case statement the condition is tested by the switch statement. It is
followed by the list of cases. Each case have the particular constant value, when a correct match is found
a block of statements associated with that case is executed.
Syntax:-
switch (expression)
{
case < lable 1 > : statement 1;
break;
case < lable 2 > : statement 2;
break;
case <lable n >: statement n;
break;
default: statement-x;
}
W.A.P. to read two numbers and person addition, subtraction,division and multiplication.
# include < iostream.h >
void main ( )
{
int ch, a,b,c;
cout<< “Enter two numbers”;
cin>>a>>b;
cout<< “\n1. Addition \n 2. subtraction \n 3. multiplication \n 4.division\n”);
cout<< “\n Enter ur choice (1.4)\n’;
cin>>ch;
switch(ch)
{
case 1: c=a+b;
cout<< “\n Addition of 2 numbers”<<c;
break;
case 2: c= a-b;
cout<< “\n subtraction of 2 numbers”<<c;
break;
case 3: c=a*b;
cout<< “\n multiplication of 2 numbers”<<c;
break;
case 4: c= a/b;
cout<< “\n division of 2 numbers “<<c;
break;
default: cout<< “\n match is not found”;
}
}
2.LOOPING STRUCRURES:-
i) while loop:- The while loop checks whether the test expression is true or not. If it is true, code/s inside
the body of while loop is executed,that is, code/s inside the braces { } are executed. Then again the test
expression is checked whether test expression is true or not. This process continues until the test
expression becomes false.
Syntax: while(condition)
{
statement;
increment/decrement;
}
W.A.P. to print numbers from 1 to 10 using while loop.
# include < iostream.h >
void main( )
{
int i=1;
while(i<=10)
{
cout<< i<<end l;
i++;
}
}
ii) Do-while:- The do-while is called bottom tested loop or exit control loop The do...while Loop is
similar to while loop with one very important difference. In while loop, check expression is checked at
first before body of loop but in case of do...while loop, body of loop is executed first then only test
expression is checked. That's why the body of do...while loop is executed at least once.
Syntax:-
do
{
statements;
increment/decrement;
} while (condition);

W.A.P. to print numbers from 1 to 10


# include < iostream.h >
void main( )
{
int i=1;
do
{
cout<< i<<end l;
i++;
}while (i < = 10);
}

iv) For Loop:- It is a popular and simple loop statement. It is used to reduce source code length. The
initialization statement is executed only once at the beginning of the for loop. Then the test expression is
checked by the program. If the test expression is false, for loop is terminated. But if test expression is true
then the code/s inside body of for loop is executed and then update expression is updated. This process
repeats until test expression is false

Syntax:-
for(initialization statement; test expression; update statement)
{ code/s to be executed;
}

W.A.P. to print numbers from 1 to 10.


# include < iostream.h >
void main( )
{
int i;
for( i=1; i<=10; i++)
{
cout<< i<< end l;
}
}
v) Goto statement:- In C++ programming, goto statement is used for altering the normal sequence of
program execution by transferring control to some other part of the programme

Syntax

goto label;

... ..

... ..

label: statement;

Ex:- goto mn;


The lable name must be followed by colon where we create branch.
In goto statements there are two types of jumpings. They are forward jumping and backward
jumping.
If the label name appears after the goto label then the statements in between will be skipped. This type
of jumping is called “forward jumping”.
If the name is appears before the goto label statement, then same set of statements will be executed
repeatedly. This type of jumping is known as “Back ward” jumping.

C++ Tokens

As we know that Software is a Program. And a Program is that which Contains set of instructions, and an
Instruction contains Some Tokens. So Tokens are used for Writing the Programs the various Types of
Tokens those are contained by the Programs.
As in the English language, in a paragraph all the words, punctuation mark and the blank spaces are
called Tokens. Similarly in a C++ program all the C++ statements having Keywords, Identifiers,
Constants, Strings, Operators and the Special Symbols are called C++ Tokens. C++ Tokens are the
essential part of a C++ compiler and so are very useful in the C++ programming. A Token is an
individual entity of a C++ program.

For example, some C++ Tokens used in a C++ program are:

Reserve: words long, do if, else etc.

Identifiers: Pay, salary etc.

Constant: 470.6,16,49 etc.

Strings: "Dinesh", "2013-01" etc.

Operator: +, *, <, >=, &&,11, etc

Special symbols: 0, {}, #, @, %, etc.

DECLARATION OF A VARIABLE:-
A variable can hold the value that can be changed. The variables must be declare before they are
used in the program and the declaration of the variable can appear anywhere in the program in C++. This
makes the program much easier to write and reduce the error that may cause because of moving up and
down.
Syntax:- Data type variable name;
Ex:- 1. int m1,m2;
2.char sname(20);

For Naming a Variable There are Some Specific Rules

• A Variable name is any Combination of 1 to 8 alphabets digits or underscore.


• The First Character in the Variable name must be an alphabet
• No Commas or blanks spaces are allowed in variable name
• No Special Symbols are used in the name of the Variable.

Dynamic initialization of a variable:- One additional feature of C++ is that it permits the initialization
of a variables at runtime. This is referrred to as dynamic initialization. This means in C++ a variable can
be initialized at runtime.
Ex:- int tot = m1,m2,m3;
Both the declaration and initialization of variable can be done simultaneously
Reference Variable:- C++ introduces a new kind of a variable known as the reference variable. A
reference variable provides an alternative name ( alias name ) for the previously defined variable.
Syntax:- data type &reference name = variable name;
Ex:- int total= 100;
int &sum=total;
it represents that total is a integer type variable, sum is the alternative name declared to represent the
variable total. If we make the variable sum a reference to the variable total then sum and total can be used
interchangeable or alternatively to represent that variable. The statements cout<<total; and cout<< sum;
both print the value 100.
Expressions:- An expression is a combination of operators, constants, variables, arranged as per the rules
of the language to produce a value. It may also include function call which return value.
Expressions are of seven types:
1. Constant Expressions 5.Relational Expressions.
2.Integral Expressions 6.Logical Expressions.
3.Float Expressions 7.Bit wise Expressions
4.Pointer Expressions 8.Compound Expressions.

A combination of variables, constants and operators that represents a computation forms an expression.
Depending upon the type of operands involved in an expression or the result obtained after evaluating
expression, there are different categories of an expression. These categories of an expression are
discussed here.

• Constant expressions: The expressions that comprise only constant values are called constant
expressions. Some examples of constant expressions are 20, ‘ a‘ and 2/5+30 .

• Integral expressions: The expressions that produce an integer value as output after performing all types
of conversions are called integral expressions.

For example, x, 6*x-y and 10 +int (5.0) are integral expressions. Here, x and yare variables of type into

• Float expressions: The expressions that produce floating-point value as output after performing all
types of conversions are called float expressions.

For example, 9.25, x-y and 9+ float (7) are float expressions. Here, x 'and yare variables of type float.

• Relational or Boolean expressions: The expressions that produce a bool type value, that is, either true
or false are called relational or Boolean expressions.

For example, x + y<100, m + n==a-b and a>=b + c .are relational expressions.

• Logical expressions: The expressions that produce a bool type value after combining two or more
relational expressions are called logical expressions.
For example, x==5 &&m==5 and y>x I I m<=n are logical expressions.

• Bitwise expressions: The expressions which manipulate data at bit level are called bitwise expressions.
For example, a >> 4 and b<< 2 are bitwise expressions.

• Pointer expressions: The expressions that give address values as output are called pointer expressions.
For example, &x, ptr and -ptr are pointer expressions.

Here, x is a variable of any type and ptr is a pointer.

• Special assignment expressions: An expression can be categorized further depending upon the way the
values are assigned to the variables.

• Chained assignment: Chained assignment is an assignment expression in which the same value is
assigned to more than one variable, using a single statement. For example, consider these statements.

a = (b=20); or a=b=20;

In these statements, value 20 is assigned to variable b and then to variable a. Note that variables cannot be
initialized at the time of declaration using chained assignment. For example, consider these statements.

int a=b=30; // illegal

int a=30, int b=30; //valid

• Embedded assignment: Embedded assignment is an assignment expression, which is enclosed within


another assignment expression. For example, consider this statement

a=20+(b=30); //equivalent to b=30; a=20+30;

In this statement, the value 30 is assigned to variable b and then the result of (20+ 30) that is, 50 is
assigned to variable a. Note that the expression (b=30) is an embedded assignment.

Compound Assignment: Compound Assignment is an assignment expression, which uses a compound


assignment operator that is a combination of the assignment operator with a binary arithmetic operator.
For example, consider this statement.

a + =20; //equivalent to a=a+20;

In this statement, the operator += is a compound assignment operator, also known as short-hand
assignment operator.

Data types:- The kind of data that variables may hold in a programing language is called the datatype.
C++ offers a set of data types. They can be classified into the following three categories.
1.User defined data type
2.Built in data type
3.Derived data type
C++ datatypes

User define dataBuilt in data type


type Derived datatypes
Structure Array
Union Integral type void Floating type
` Functions
Class Pointers
Enumeration
int char float double

1.USER DEFINE DATATYPE:- Structure, Union and Class: Structure and union are the significant
features of C language. Structure and union provide a way to group similar or dissimilar data types
referred to by a single name. However, C++ has extended the concept of structure and union by
incorporating some new features in these data types to support object -oriented programming.

C++ offers a new user-defined data type known as class, which forms the basis of object-oriented
programming. A class acts as a template which defines the data and functions that are included in an
object of a class. Classes are declared using the keyword class. Once a class has been declared, its object
can be easily created. .

Enumeration type:- An enumerated datatype is a user defined data type which provides a way for
attaching names to numbers, there by increasing comprehensibility of the code. The “enum” keyword
automatically enumerates a list of words by assigning the values 0,1,2,----. This facility provides an
alternative, means for creating symbolic constants.
Ex:- enum shape { circle, square, triangle};

2.BUILT IN DATATYPE-

The basic (fundamental) data types provided by c++ are integral, floating point and void data type.
Among these data types, the integral and floating-point data types can be preceded by several type
modifiers.The various modifiers are short, long, signed and unsigned. By default the modifier is signed.

Integral Data Type: The integral data type is used to store integers and includes char (character) and int
(integer) data types.

Char: Characters refer to the alphabet, numbers and other characters (such as {, @, #, etc.) defined in the
ASCII character set. In C++, the char data type is also treated as an integer data type as the characters are
internally stored as integers that range in value from -128 to 127. The char data type occupies 1 byte of
memory (that is, it holds only one character at a time)

Int: Numbers without the fractional part represent integer data. In C++, the int data type is used to store
integers such as 4, 42, 5233, -32, -745. Thus, it cannot store numbers such as 4.28, -62.533. The various
integer data types with their size and range are listed in Table

Floating-point Data Type: A floating-point data type is used to store real numbers such as 3 .28, 64.
755765, 8.01, -24.53. This data type includes float and double' data types.
Void: The void data type is used for specifying an empty parameter list to a function and return type for a
function. When void is used to specify an empty parameter list, it indicates that a function does not take
any arguments and when it is used as a return type for a function, it indicates that a function does not
return any value..

3.DERIVED DATATYPES:- The three derived types in C++ are arrays functions,Pointers.
Arrays:- The application of arrays in C++ is a similar to that in C. The only exception is the way
character arrays are initialized. When initializing a character in C, the compiler will allow us to declare
the array size as the exact length of the string constant.
Ex: char str[3] = “xyz”;
It is assumed that the programmer intends to leave out the null character ie., “\o” in the definition . But
in C++ the size should be one longer than the number of characters in the string.
Ex: char str[4] =”xyz”;
Pointers:- Pointers are declared and initialized in C, C++ adds the concept of constant pointer to a
constant.
Ex: char * const ptr1 = “abc”;

OPERATORS IN C++

In addition to the operators like arithmetic operators, relational operators, logical operators, the
conditional operator and assignment operators that most of the languages support, C++ provides various
new operators that are given in Table

New operators

Scope resolution operator ::


new Memory allocation operator
endl Line feed operator
setw Field width operator
delete Memory release operator

Scope Resolution Operator (::)

The scope resolution operator : : is a special operator that allows access to a global variable even though
the local variable has the same name. To understand the concept of scope resolution operator, consider
this example.

A program to demonstrate the use of scope resolution operator

#include<iostream>

using namespace std;

int x = 5;
int main ()

{ int x = 3;

cout<<”The local variable of outer block is: “<<X;

cout<<”\nThe global variable is: “<<::X;

return 0;

The output of the program is

The local variable of outer block is: 3

The global variable is: 5

new and delete: C++ provides two dynamic allocation operators new and delete to allocate and
deallocates memory at run-time respectively. The new operator is a unary operator that allocates memory
and returns a pointer to the starting of the allocated space. The syntax of allocating memory using the new
operator is

p_var= new data_type;

where,

p_ var=the name of a pointer variable

new=C++ keyword

data_type =arty valid data type of C++

For example

int *iptr; //pointer declaration

iptr=new int; //allocating memory to an int variable

(or)

int *iptr=new int i

The life-time of a variable created at run-time using the new operator is not restricted till the execution of
the program. Rather, it remains in the memory until it is explicitly deleted using the delete operator.
When a dynamically allocated variable is no longer required, it must be destroyed using the delete
operator to ensure safe and efficient use of memory.
The syntax for using the delete operator is

delete p_var;

For example, to delete the pointers iptr and fptr of types int and float respectively, these statements are
used.

delete iptr;

delete fptr;

Manipulators:- Manipulators are operators that are used to format the data display. The most commonly
used manipulators are “end l” and “ setw( )”.
The end l manipulator, when used in a out put statement causes a line feed to be inserted. It has the
same of fact as using the newline character “\n”.
Ex: cout<<”m=” <<m << end l << “n=” << n<< end l;
Out put: m=5, n=6.
The manipulator setw( ) specifies a filed width for printing the value of the variable.
Example programe:
# include < iostream.h >
# include <iomanip.h >
main ( )
{
int basic= 950. Allowance = 95, total= 1045;
cout <<setw(10) << “Basic =” << setw(10) << basic <<end l
<< setw(10) <<”allowance =”<< setw(10) << allowance << end l
<<setw(10) <<”total =” <<setw(10) << total << end l;
}

FUNCTIONS IN C++
A function groups a number of programs statement into a unit and gives it a name. This unit can be
invoked other parts of the program. It is very difficult to implement a large problem. A complex problem
may be decomposed into a small and easily manageable parts or modules called functions. Functions are
very useful to read, write, debug and modify the complex problem. They can also easily incorporate in the
main program. In C++, the main( ) itself is a function. That means the main( ) is invoking the other
functions to perform various task. By using functions it is possible to reduce the size of program by
calling and using them at different places in a program.
The general form of a function definition is.
return_type function_name( parameter list )
{
body of the function
}

A C++ function definition consists of a function prototype declaration and a function body. All the parts
of a function are -

Part Explanation
return_type is the type of data that function returns. It is not necessary that function will
Return Type
always return a value.
Function It is the actual name of the function. The function name and the parameter list together
Name forms the signature of the function
Parameters allow passing arguments to the function from the location where it is called
Parameters
from. Parameter list is separated by comma
Function
The function body contains a collection of statements that define what the function does.
Body
Example program:
# include < iostream.h >
void main( )
{
int x.y;
void output (int x, int y);
cout<<”This is our main program”;
output (x.y);
}
void output(int a, int b)
{
cout<<” Enter the value of a,b”;
cin>> a>>b;
int c= a+b;
cout<<c; }
Inline function:- Generally functions have memory space because all the calls to the function causes
same code to be executed. A function body need not be duplicated in memory space, it takes some extra
time.
To save execution time in short functions C++ provides a new feature called inline function.
An inline function is a function ie., expanded in line when it is invoke. That is the compiler replaces the
function call with the corresponding function cade. It is similar to macros in C. But the main drawback
with the macros is that they are not really functions and therefore, the usual error checking doesnot occur
during compilation. The inline functions are defined as follows.
Syntax:- inline function header
{
function body;
}
Ex: inline float mul(p,q)
{
return (p,q);
}
The inline function must be specified with a key word “inline”.
RULES:
1.Inline functions should be defined before main program.
2.The reserve word “inline” should appear in the function heading.
3.Inline function should be small because the speed benefits of inline function diminish as the function
grows in size.
4.The inline function should not contain control structure of loop structures.
5.The inline function does not work for recursive statements.

Example program:-
# include <iostream.h>
inline float mul(float p,float q)
{
return (p*q);
}
inline int div(int x, int y)
{
return (x/y)
}

Void main()
{
float p=3,q=4.8;
int x=6,y=3;
cout <<”Multiplication of 2 numbers” << mul(p,q);
cout <<”Division of 2 numbers” << div(x,y);
getch( );
}
Default arguments:- In C++ programming, you can provide default values for function parameters. The
idea behind default argument is very simple. If a function is called by passing argument/s, those
arguments are used by the function. But if all argument/s are not passed while invoking a function then,
the default value passed to arguments are used.

Note :- In default arguments the trailing arguments can have defined values and therefore we must add
from right to left. We cannot provide a default value to a particular argument in the middle of an
argument list.
Ex:- float amount (int p, int t=7, float r=0.15); ||legal.
float amount (int p, int t=7, float r); || illegal.
Advantages:-
1.We can use default arguments to add new parameters to the existing function.
2.Default arguments can be used to combine similar function into one.
Example program:-
# include <iostream.h>
void main( )
{
float amount (int p=5000, int t=7, float r=0.15);
float value1, value2,value3;
cout <<”value 1=” <<amount ( ) <<end l;
cout <<”value 2=” <<amount ( 3000,1) <<end l;
cout <<”value 3=” <<amount (6000,3,0.15) <<end l;
}
float amount (int p, int t,float r)
{
float si;
si+ (p*t*r)/100;
return (si);
}
FUNCTION OVERLOADING:- Over loading refer to the use of same thing for different purposes. C++
also permits over loading of functions. This means we can use the same function name to create functions
that perform a variety of different task. This is known as function overloading or function polymorphism
in Oop.
By using the concept of function overloading we can design a family of functions with same function
name but with different argument list. Function would perform different operations depending on the
argument list in the function call.
/* Example of function overloading */
int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }

All 4 functions mentioned above are overloaded function. It should be noticed that, the return type of all 4
functions is same,i.e, int. Overloaded function may or may not have different return type but it should
have different argument(either type of argument or numbers of argument passed

Example program:-
/*Calling overloaded function test() with different argument/s.*/
#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;

test(a);
test(b);
test(a, b);

return 0;
}

void test(int var) {


cout<<"Integer number: "<<var<<endl;
}

void test(float var){


cout<<"Float number: "<<var<<endl;
}

void test(int var1, float var2) {


cout<<"Integer number: "<<var1;
cout<<" And float number:"<<var2;
}

Output

Integer number: 5
Float number: 5.5
Integer number: 5 And float number: 5.5

CALL BY REFERENCE:- Provision of reference variables in C++ permits us to pass parameters to the
function by reference. When we pass arguments by reference, the formal arguments in the called function
become alias to the arguments in the calling function. This means that when the function is working with
its own arguments, it is actually working on the original data.
Example program:-
# include <iostream.h>
void swap ( int *x, int *y);
void main( )
{
int a,b;
cout <<”Enter a,b values”;
cin>>a>>b;
swap (&a, &b);
getch( );
}
Void swap(int *x, int *y)
{
Int t;
t= *x;
*x= *y;
*y= t;
cout<<”a=”<<*x;
cout<<”b=”<<*y;
}
CLASS AND THE OBJECTS
The most important feature of C++ is the “class”. A class is an extension of the idea of structure used
in C.
C++ supports all the features of structure as defined in C. But C++ has expanded its capabilities
further to satisfy its Oop philosophy. It attempts to bring the user defined types as close as possible to the
built in types and also provides a facilities to hide the data which is one of the main principal of Oops.
A class is the collection of related data and function under a single name. A C++ program can have
any number of classes. When related data and functions are kept under a class, it helps to visualize the
complex problem efficiently and effectively

When we define a class, we define a blueprint for a data type. This doesn't actually define any data, but it
does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object

A Class is a blueprint for objects

When a class is defined, no memory is allocated. You can imagine like a datatype.

int var;

The above code specifies var is a variable of type integer; int is used for specifying variable var is of
integer type. Similarly, class are also just the specification for objects and object bears the property of that
class.
Defining the Class in C++

Class is defined in C++ programming using keyword class followed by identifier(name of class). Body of
class is defined inside curly brackets an terminated by semicolon at the end in similar way as structure.

A class is a way to bind the data and it associated function together .It allows the data to be hidden if
necessary from external use. When defining a class we are creating a new abstract data type that can be
created as any other built in type. Generally a class specification has
1. Class declaration.
2. Function definition.
Class declaration describes the dypes and scope of its members.
The class function definitions describes how the class functions are implemented the general form of class
definition is.
Syntax:
Class < class name>
{
Private:
Variable declaration;
Function declaration;
Public:
Variable declaration;
Function declaration;
};
The members that have been declared as private can be accessed only from within the class.
On the other hand public members can be accessed from outside the class also. The data hiding using the
private declaration is the key feature of object oriented programming. The use of key word private is
optional. If both the labels (key word ) are missing then by default, all the members are private. A class is
completely hidden from the outside world .Functions with in the class are known as “member functions”
Only the member functions can have access to the private data members .
Example:- class item
{
private :
int num;
float price;
public:
void get data ( );
void put data( );
};
In this example the class name is item. This name now become a new type identifier that can be used to
declare instance or objects of that class type. Item contains two data members and two member functions.
The data members are private and member functions are public .
Creating objects:-
Once a class have been declared we can create the variables of that type using the class name for
example:
item x;
it creates a variable ‘x’ of type item. In C++ the class variables are known as objects.
Accessing class members:-
The private data of a class can be accessed only through the member functions of that
class .The main( ) function cannot contain statement “num” and “price” directly.The following is the
format for calling a member function.
Syntax:- object name . function name ( Argument list );
Ex: - x.getdata ( int num, float price );
x getdata ( 100, 25.3 );
The above function call statement assigns the value of 100 to num and 25.3 to price.
Defining member function:-
Members function can be defined in two places.
1. Outside the class definition.
2. Inside the class definition.
1.out side the class definition:-
Members functions that are declared inside a class have to be defined separately outside the class. These
definitions are very much like to the normal functions. They should have a function header and function
body.. An important difference between member function and a normal function is member function
incorporates a member ship identification label in the header. This label tells the compiler to which class
the function belongs .The general form of a member function definition is.
Syntax: return type class name :: function_name ( Argument list )
{
function body;
}

Explanation:-
The member ship label “class name” tells the compiler that the function name belongs to
the particular class. The symbol “ :: “ is called “scope resolution operator”.
Member function can access the private data of a class. A member function can call
another member functions directly without using a dot operator.
Ex:- write a program to display the room details of a hotel defining the member functions outside the
class.
# include < iostream.h >
class hotel
{
Private:
int rno, rrent;
char cname [20];
char rtype[10];
Public :
void getdata( );
void display( );
};
void hotel :: get data( )
{
cout <<”enter customer name, room type, room number, room rent” <<end l;
cin >> c name >> r type >> r no >>r rent;
}
void hotel :: display ( ){
cout << “\n customer name is “ << c name << end l;
cout << ”\n Room type is “ << r type << end l;
cout << ”\m Room number is” << r no << end l;
cout << “\n Room rent is” << r rent << end l;
}
void main ( )
{
clrscr ( );
hotel h1,h2;
h1 getdata( );
h1 display( );
h2 getdata( );
h2 display( ); getch();
2. Inside the class definition;- Another method of definition a member function is to replace the
function declaration by the function definition inside the class.
Syntax: class < class. name >
{
Public:
function name ( argument list )
{
function body;
}
When a function is defined inside a class it is treated as “inline function”. Therefore all the restrictions
and limitations that a applicable to an in line function are also applicable here.
Ex:- W.A.P to display the name of the person and his date of birth.
# include < iostream.h >
class dob
{
private:
char name[20];
int date,month, year;
public:
void get data( )
{
cout << “\n enter name, date, month, year”;
cin >> name >> date >> month year;
}
void display( )
{
cout << “\n person name is “ << name << end l;
cout << “\n date of birth is “ << date << “_” << month << “_” << year;
}
};
Void main()
{
clrscr( );
dob p;
p.get data( );
p.display( );
getch( ); }
Nesting of member function:-
The member functions can be called by using its name inside other member functions of the same
class. This is known as nesting of member functions.
Example:- W.A.P to find the largest of two numbers
# include < iostream.h >
# incluce < conio.h >
class big
{
private:
int a,b;
public:
void getdata( );
void display( );
int largest( );
};
void big :: getdata( )
{
cout << “Enter values for a and b “ << end l;
cin >> a >>b;
}
void big :: display( )
{
cout << “ Largest value is “ << largest( );
}
int big :: largest ( )
{
if ( a>b)
return ( a );
else
return ( b )
}
main ( )
{
clrscr( );
big b;
b.getdata( );
b. display( ); getch( ); }
STRINGS AND ARRAYS
Arrays with in class:-
The arrays can used as member variables in a class .The following definition is valid.
Ex:- const int size = 50;
class item
{
int a[size];
public:
void input( );
void display ( );
};
The array variable ‘a’ is declared as a private member of the class item. This can be used in the member
functions like any other variables.
W.A.P to generate the grade of a student by calculating the avg .
# include < iostream.h >
# include < conio.h >
class student
{
int sno, tot, m[10], n;
char sname[25], grade[15];
float avg;
public:
void getdata( );
void cal( );
void grade( );
};
void student :: getdata( )
{
cout << “in enter sno,sname”;
cin>> sno >> sname;
cout <<”\n Enter how many subjects marks u Want”;
cin>>n;
for ( int i=0; i<n; i++ )
{
cout << “\n enter marks “;
cin >> m[i];
}
}
void student :: cal( )
{
int i,tot =0;
for ( i=0; i<n; i++ )
{
tot = tot +m[i];
}
cout <<”\n total =” <<tot;
avg =tot\n;
cout <<”\n average =” <<avg;
}
void student :: grade( )
{
if ( ( avg >80) && (avg<100) )
{
strcpy (grade,”Dist”);
}
else if ( (avg >60) && (avg <80) )
{
strcpy (grade ,”First”);
}
else if ( ( avg >45) && (avg<60) )
{
strcpy (second, “Second”);
}
else if ( ( avg > 35) && (avg < 45) )
{
strcpy (grade, “Third”);
}
else
{
strcpy (grade, “Fail”);
}
cout <<”\n Grade =” << grade;
}
void main( )
{
student s;
s.get data( );
s.cal( );
s.grade( );
getch( );
}

Array of object:-
An array can be of any datatype including the structure. Similarly we can also have arrays of variables
that are of type class. Such variables are called “Array” of objects.
Syntax:- class < class_name >
{
private :
data members;
mamber functions;
public:
data members;
members functions;
}
class_name object_name[size];
where ‘size’ is a user defined size of the array of the class object. Since an array of object behaves like
any other array, we can use the usual array accessing members. We access the individual elements
through the dot operator to access the member function.
Example:-W.A.P. to calculate the net salary for different employees.
# include < iostream.h >
class emp
{
int eno,da, hra,ba, net sal;
char ename[15];
public:
void getdata ( );
void cal( );
void disp( );
};
void emp :: getdata( )
{
cout <<”Enter eno, ename,ba,hra,da” <<end l;
cin >> eno>> ename>> ba>> hra>> da;
}
void emp :: cal( )
{
net sal = da+hra+ba;
}
void disp ::disp()
{
cout <<”eno=” << eno<< end l << “ename=” << ename << end l << “net salary =” <<net sal;
}
void main( )
{
emp e[20];
int n,i;
cout <<”\n enter how many employees do U want”;
cin >> n;
for ( i=1; i<=n; i++ )
{
e[i]. getdata( );
e[i]. cal( );
e[i]. disp( );
}
}
STATIC DATA MEMBERS:
We can define class members static using static keyword. When we declare a member of a class as
static it means no matter how many objects of the class are created, there is only one copy of the static
member.
A static member variable has certain special characteristics. They are.
1.It is initialized to zero. When the first object of its class is created. No other initialization is permitted.
2. Only one copy of that member is created for the entire class and is shared by all the objects of that class
no matter how many objects are created.
3. It is a visible only with in the class, but its life time is in the entire program.
4. The static variable created inside the class. It should be defined outside the class by using the class
name and scope resolution operator.

Syntax:
class class_ name
{
private:
static variable declaration;
variable declaration;
public:
variable declaration;
member function declaration;
}
Return type class name :: static variable name;
The type and scope of each static member variable must be defined outside the class definition.
This is necessary because the static date member is stored separately rather than as a part of an object;
Static variable are also known as class variables. Because they are associated with the class rather
than any object.
Example:-W.A.P. to illustrate the use of static data member.
#include<iostream.h>
#include<conio.h>

class stat
{
int code;
static int count;

public:
stat()
{
code=++count;
}
void showcode()
{
cout<<"\n\tObject number is :"<<code;
}
static void showcount()
{
cout<<"\n\tCount Objects :"<<count;
}
};

int stat::count;

void main()
{
clrscr();
stat obj1,obj2;

obj1.showcount();
obj1.showcode();
obj2.showcount();
obj2.showcode();
getch();
}
Output:
Count Objects: 2
Object Number is: 1
Count Objects: 2
Object Number is: 2
Static member function:-
By declaring a function member as static, you make it independent of any particular object of the class. A
static member function can be called even if no objects of the class exist and the static functions are
accessed using only the class name and the scope resolution operator ::.
A member function ie; declared using the key word “static” will become static member function. A static
member function has the following properties.
1.A static member function can be have access to only other static member functions (or) variables
declared in the same class.
2. The static member function can be called using the class name as follows.
Syntax: class name :: function name( );
Example:- W.A.P to illustrate the use of static member function

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

class test
{
int code;
static int count;
public :
void setcode(void)
{
code= ++count;
}
void showcode(void)
{
cout<<"object number"<<code<<endl;
}
static void showcount(void)
{
cout<<"count"<<count<<endl;
}
};
int test::count;

int main()
{
clrscr();
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
return(1);
}

OUTPUT

Count 2
Count 3
Object number 1
Object number 2
Object number 3

Friend function:-

One of the important concept of OOP is data hiding, i.e., a nonmember function cannot access an object's
private or protected data. But, sometimes this restriction may force programmer to write long and
complex codes. So, there is mechanism built in C++ programming to access private or protected data
from non-member function which is friend function and friend class.

If a function is defined as a friend function then, the private and protected data of class can be accessed
from that function. The complier knows a given function is a friend function by its keyword friend. The
declaration of friend function should be made inside the body of class (can be anywhere inside class
either in private or public section) starting with keyword friend.

Rules of friend function

1.It is not in the scope of the class to which it has been declared as a friend.
2.Since it is not in the scope of the class, it cannot be called using the object of that class.
3. It can be invoke like a normal function without the help of any object.
4. Unlike member function, it cannot access the member variables directly, and as such it has to use an
object name and dot operator with each member variable.
5. It can be declared either in public or the Private part of the class.
6.The function definition cannot have the key word friend or the scope resolution operator ( :: ).
7. The friend function has objects as the function arguments.
The syntax for the friend function is
Syntax: Friend return type function name (argumentlist).
W.A.P. to calculate the mean of 2 numbers using friend function.
#include < iostream.h >
#include < conio.h >
class sample
{
int a,b;
Public:
Void get data( )
{
Cout <<” \n Enter a and b values”;
Cin>> a>> b;
}
Friend int mean ( sample s);
};
int mean ( sample s)
{
return (s.a+s.b)/2;
}
void main ( )
{
sample s;
clrscr( );
s.getdata( );
cout <<”mean=” << mean( s )<< end l;
getch( );
}

Member functions of one class can be friend of another class. In such cases they are defend using the
scope resolution operator as shown bellow.
Class x
{
--------
-------
int fun1( );
-------
-------
};
Class y
{
-------
-------
friend int x:: fun1( );
------
------
};
We can also declare all the member function of one class as the friend frnction of another class. In
such cases the class is called “friend class”.

Class x
{
------
------
Public:
Data member;
Member function;
------
------
};
Class y
{
-------
-------
friend class x;
-------
-------
};

CONSTRUCTORS AND DESTRUCTORS


C++ provides a special member function called the constructor which enables an object to be
initialized by itself when it is created. This is known as automatic initialization of objects. It also provides
another member function called the “Destructors” that destroys the objects when they are no longer
required.
Constructor:-
A constructor is a special member function whose task is to initialize the objects of its class. it is a
special member function and its name is same as the class name. The constructor is invoked whenever an
object of its associated class is created. It is called constructor because it constructs the values of data
members of the class.
A constructor is declared and defined as follows
Class integer
{
int m,n;
Public:
integer (void);
};
integer ::integer (void)
{
m=0;
n=0;
}
When a class contains a constructor like the one above it is guaranteed that an object created by the
class will be initialized automatically.
For example- integer num1,
object num1 is created;
Here the declaration not only creates the object num1 of type integer but also initializes its data
members m and n to zero. There is no need to write any statement to invoke any constructor function. A
constructor that accepts no parameters is called the “Default constructor”. If no such constructor is
defined then the compiler supplies a default constructor.
The constructor function have some special characteristics. They are.
1.They should be declared in the public section.
2.They are invoked automatically when the objects are created.
3.They do not have return types, not even void.
4.They cannot be inherited through a derived class can call the base class constructor.
5.Constructors cannot be virtual.

Parameterized constructor:- The constructor integer ( ), defined above initializes the data member of
the object to zero. However, it may be necessary to initialize the various data elements of different objects
with different values when they are created. C++ permits us to achieve this by passing arguments to the
constructor function when the objects are created. The constructors that can takes arguments are called”
Parameterized Constructors”. The parameterized constructor can be defined as follows.
class integer
{
int m,n;
Public:
integer ( int x, int y )
{
m=x;
n=y;
}
};
( or )
class integer
{
int m,n;
Public:
integer ( int n, int y ); // constructor declared
};
integer :: integer ( int x, int y ) // constructor defined
{
m=x;
n=y;
}
When a constructor has been parameterized the object declaration statement such as integer num1 may
not work. We must pass the initial values as arguments to the constructor function, when an object is
declared,
1.By calling the constructor explicitly.
2.By calling the constructor implicitly.
The following declaration illustrates the first method.
integer num1= integer (0,50);
This method creates an integer object num1 and passes the values 0 and 50 to it.

The second method is implemented as follows


integer num1 (0,50);
This method some times call short hand method is used very often as it is shorter , looks better and easily
to implement.
Note:- When the constructor is parameterized we must provide appropriate arguments for constructor .
W.A.P. to demonstrate the passing of arguments to the constructor function.
#include < iostream.h>
#include < conio.h>
class integer
{
int m,n:
public:
integer ( int, int );
void display( );
};
integer :: integer ( int x, int y ) // constructor defined
{
m=x; n=y;
}
void integer :: display( )
{
cout << “m+” m<< “n=” << n<< end l;
}
void main( )
{
integer int 1=integer (50,100); // explicity call
int 1.display( );
integer int2 (30,70); // implicitly call
int2. Display( );
}

W.A.P. to input product no, pname, no.of product sold, cost of each product. Calculate the bill
amount based on the discount 10% if bill amount =1000, otherwise no discount. Print bill amount .
#include < iostream.h>
#include < conio.h>
class product
{
char pname[15];
int pno,nps,cp.bamt;
float disc,nba;
public:
product ( )
{
disc=0;
}
void getdata( )
{
cout <<”enter product no, product name , no.of product sold, cost of each product”;
cin >> pno >> pname >> nps >>cp;
}
void cal( )
{
b amt= nps x cp;
if (bamt>= 1000)
{
disc =0.1 * b amt;
nba = bamt- disc;
cout <<” Net bill amount=” << nba;
}
else
{
cout <<”bamt =”<< bamt<<”\n no dis count “ << end l;
}
};
void main( )
{
product p1;
clrscr( );
p1.getdata( );
p1.cal( );
getch( );
}
Copy constructor:- The copy constructor is used to declare an initialize an object from another object.
The process of initializing through a copy constructor is called “Copy initializing”. A copy constructor
takes a reference to an object of the same class as itself as an argument.

Syntax

class_Name (const class_Name &obj)


{
// body of constructor
}

Eg:
#include < iostream.h>
#include < conio.h>
class node
{
int id;
public:
code( )
{
}
code (int a)
{
id =a;
}
code ( code & x)
{
id=x.id;
}
void display( )
{
cout << id;
}
};

void main( )
{
code a(100); // object A is created or initialsed
code b(a); // copy constructor called
cout <<”id of A is “;
a.display ( );
cout <<” \n id of B is “;
b.display( );
}
Note:- A reference variable has been used as an object to the copy constructor. We cannot pass the
arguments by value to a copy constructor.
Multiple constructor in a class:- We can declare different types of constructors in a class.
Ex:-
#include < iostream.h>
#include <conio.h>
class integer
{
int m,n;
public:
void display( );
integer( )
{
m=0, n=0;
}
integer ( int x, int y)
{
m=x; n=y;
}
integer (integer & i)
{
m=i.m;
n=i.n;
}
};

void main( )
{
integer i1;
i1.display( );
integer i2(100,200);
integer i3(i2);
i2.display( );
i3.display( );
}
In the first case the constructor itself supplies the data value and vo values are passed by the calling
program. In the second case the function call passes the appropriate values from main function. This
declares three constructors for a integer object. The first constructor receives no argument. For example
the declaration integer i1 would automatically invok the first constructor and set both m an n of i1 to zero.
The statement integer i2 (100,200) ; would call the second constructor which will initialize the data
members m and n of i2 to 100 & 200 representively. Finally the statement integer i3(i2); would invoke
the third constructor which copies the values of i2 into i3.
Dynamic initialization of objects:-
Class objects can be initialized dynamically to i.e; initial value of an object may be provided during
runtime. One advantage of dynamic initialization is that we provide the memory space for the object at
runtime. If we pass the values to the objects at the runtime then we call it as a dynamic initialization of
object.
A program for dynamic initialization of object:-
#include < iostream.h>
#include< conio.h>
class integer
{
int m,n;
public:
integer (int b, int v)
{
m=b; n=v;
}
void display( )
{
cout <<”m=” <<m<<end l;
cout <<”n=” <<n<< end l;
}
};
void main( )
{
int b,v;
cout<< “enter b and v values”;
cin >> b>>v;
integer i1 (b,v); // inplicity
i1.display( );
vout<<”enter b & v values”;
vin >>b >>v;
integer i2= integer (b,v);
i2.display( );
}
Destructors:- A Destructor is used to destroy the objects that have been created by constructor. Like a
constructor the destructor is a member function whose name is same as the class name. But it is produced
by tilde(~). For example the destructor for the class integer can be defined as
~ integer( )
{
}
A destructor neither takes any arguments nor does it return any value. It will be invoked directly by the
compiler upon that is no longer accessible. It is a good practice to declare destructors in a program since it
releases memory space for future use.
#include <iostream>

using namespace std;

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;
};

// Member functions definitions including constructor


Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}

void Line::setLength( double len )


{
length = len;
}

double Line::getLength( void )


{
return length;
}
// Main function for the program
int main( )
{
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Object is being created


Length of line : 6
Object is being deleted

6. OPERATOR OVERLOADING
Operator overloading is one of the many existing features of C++ language. It is an important technique
that has enhance the power of extendibility of C++. We know that C++ tries to make the user defined data
type behave as close as possible to the built in types.

The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++
language. For example: If you want to add two integers then, + operator is used. But, for user-defined
types(like: objects), you can define the meaning of operator, i.e, you can redefine the way that operator
works. For example: If there are two objects of a class that contain string as its data member, you can use
+ operator to concatenate two strings. Suppose, instead of strings if that class contains integer data
member, then you can use + operator to add integers. This feature in C++ programming that allows
programmer to redefine the meaning of operator when they operate on class objects is known as operator
overloading.

Why Operator overloading is used in C++ programming?

You can write any C++ program without the knowledge of operator overloading. But, operator operating
are profoundly used by programmer to make a program clearer. For example: you can replace the code
like: calculation = add(mult(a,b),div(a,b)); with calculation = a*b+a/b; which is more readable and easy to
understand.

How to overload operators in C++ programming?

To overload a operator, a operator function is defined inside a class as:

The return type comes first which is followed by keyword operator, followed by operator sign,i.e., the
operator you want to overload like: +, <, ++ etc. and finally the arguments is passed. Then, inside the
body of you want perform the task you want when this operator function is called.

This operator function is called when, the operator(sign) operates on the object of that class class_name.

The process of overloading involves the following steps.


1.Create a class that defines the data type that is to be used in operator overloading operation.
2.Declare the operator function operator op( ) in th public part of th class. It may be either a friend
function or a member function.
3.Define the operator function to implement the required operator.
Rules for overloading operators:-
1.Only existing operators can be overloaded. New operators cannot be overloaded.
2.The overloaded operator must have at least one operator i.e, that is of user defined type.
3.We cannot change the basic meaning of an operator that is we cannot predefine the plus “+” operator to
subtract one value from the other.
4.Overloaded operators must follow the syntax rules, that govern its use such as the no.of operators,
precedence and associativity.
For example, the multiplication operator will have higher precedence than the addition operator.

5.There are some operators that cannot be overloaded such as


Size of - size of operator
. - membership operator
.* - pointer to member operator
?: - conditional operator
:: - scope resolution operator.
6.We cannot use friend function to overload certain operators. Members function can be used to overload
them. They are.
= - Assignment operator.
() - Function call operator.
[ ] - subscripting operator.
- class member access operator.

7.Unary operator overloaded by means of a member function, takes no explicit arguments and return no
explicit value but those overloaded by means of a friend function take one reference argument.
8.Binary operators overloaded through a member function take one explicit arguments and those which
are overloaded through a friend function take two explicit argument.
9.When using binary operators which are overloaded through a member function, the left hand operator
must be an object of relevant class.
10.Binary arithmetic operators such as +, -, * , /, \, must explicitly return a value. They must not attempe
to change their own arguments.
W.A.P. to overload binary operator ‘+’ using member function.
#include <iostream>
#include <conio.h>
using namespace std;
class Complex
{
int real,img;
public:
Complex() //default constructor
{
real=0;
img=0;
}
Complex(int r,int ig) //Parametrized constructor
{
real=r;
img=ig;
}
Complex operator + (Complex &c) //Memory consumption is minimised by the use of &
{ //Class name as the derived type
Complex t;
t.real=real+c.real;
t.img=img+c.img;
return t;
}
void show()
{
cout<<real<<"+i"<<img<<endl;
}
};
int main()
{
Complex c1(5,2),c2(7,3),c3;
c1.show();
c2.show();
c3=c1+c2;//need a default constructor to initialize the values for c3
c3.show();
getch();
}
We should not to the following features of this operator +( ).
1.It receives only one complex type argument explicitly.
2.It returns a complete type value.
3.It is a member function of class complex.
Here the function is expected and to add two complex values and returns a complex values as the
result. But receives only one value as arguments.
Here the statement c3=c1+c2 will invoke this function. We know that a member function can be
invoke only by an object of the same class. Here the object c1 takes the responsibility of invoking th
function and c2 places the role of an argument that is calls to the function. The above invocation
statement is equivalent to c3= c1. Operator +( c2 );
In the operator +( ) function the data members of c1 can accessed directly and the data members of
c2 using dot operator.
W.A.P to overload unary ‘++’ using member function
#include<iostream.h>
#include<conio.h>

class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}

void operator--()
{
a=--a;
b=--b;
}

void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};

void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}

Advantages of operator overloading:-


1.We can changes complex statements into simple and readable form.
2.It can be applied to userdefine data like objects of user define classes.
3. It redefines the c++ language by extending the meaning of its operators.
4.It makes code more understandable and transparent.
5.It helps C++ operators to work with objects.
6.It gives new meaning to existing operators.
7. INHERITANCE
Reusability is another important feature of object oriented programming. It is always helpful if we could
reuse something that already exist rather than typing to create the some all over again. It would not only
save time but also reduce frustration and increase reliability. For example the reuse of a class that has
already being tested, debugged and used many times can save us the effort of developing and testing the
some again.
C++ strongly supports concept of reusability. The C++ classes can be reused in several ways. The
mechanism of deriving any class form an old one is called Inheritance. The old class is referred to as the
Base class (or super or parent) class and the new one is called Derived ( or sub or child) class.
Types of inheritance:- There are 5 types of inheritance in c++ . They are.
1.Single level inheritance.
2.Multilevel inheritance.
3.Multiple inheritance.
4.Hierarchical inheritance.
5.Hybrid inheritance.
1.single level inheritance:- A derived class inherits some or all of the properties ( traits ) from the base
class is called single level inheritance. It is represented as.
A Base (or) super (or) parent class.

A Derived (or) super (or) Parent class.

2.Multilevel inheritance:- The mechanism of deriving a class from another derived class is known as
Multilevel inheritance.

A Base class

B Deieved class

C Derived class
3.Multiple inheritance:- If a class inherit peoperties from more than one class or from more than one
level is called Multiple inheritance.
Base class A B Base class

C Derived class.
4.Hierarchical inheritance:- If the properties of one class may be inherited by more than one derived
class is known as hierarchical inheritance.
A Base class

B C D
Derived class.
5.Hybrid inheritance:- It is the combination of multiple and multilevel inheritance.

Defining a derived class:-A derived class cab be defined by spefiying its relation with the base class in
addition to its own details.The general form of defining a derived class is
Syntax:-class derived class name: visibility mode base class name
{
Members of derived class
};
The colon indicates that the derived class is derived from the base classname.Visiblity mode is optional
and if present may be either private or public.The default visibility mode is private
The visibility mode specifies whether the features of base class or privately derived or publicly derived.
Eg:-
class ABC: private XYZ //private derivation
{
members of ABC
};
class ABC: public XYZ //public derivation
{
members of ABC
};
class ABC: XYZ //private derivation by default
{
member of ABC
};
Member How Members of the Base Class Appear in the Derived Class
Access
Specifier
Private Private members of the base class are inaccessible to the derived
class.
Protected members of the base class become private members of
the derived class.
Public members of the base class become private members of the
derived class.
Protected Private members of the base class are inaccessible to the derived
class.
Protected members of the base class become protected members of
the derived class.
Public members of the base class become protected members of the
derived class.
Public Private members of the base class are inaccessible to the derived
class.
Protected members of the base class become protected members of
the derived class.
Public members of the base class become public members of the
derived class.

Single inheritance
W.A.P to illustrate e single inheritance by plaicing the visibility mode public in the derived class.
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};

class Rectangle: public Shape


{
public:
float area ()
{
return (width * height);
}
};

class Triangle: public Shape


{
public:
float area ()
{
return (width * height / 2);
}
};

int main ()
{
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
cout << rect.area() << endl;
cout << tri.area() << endl;
return 0;
}

Explanation to the program using public visibility mode.


The object of the class Rectangle contains :
width, height inherited from Shape becomes the protected member of Rectangle.
set_data() inherited from Shape becomes the public member of Rectangle
area is Rectangle’s own public member

The object of the class Triangle contains :


width, height inherited from Shape becomes the protected member of Triangle.
set_data() inherited from Shape becomes the public member of Triangle
area is Triangle’s own public member
set_data () and area() are public members of derived class and can be accessed from outside class i.e.
from main()

Making a private member inherited:- We know that private member of a base class cannot be inherited
and is not available for the derived class directly. Suppose if we change the private member to public, this
would make accessible to all the other functions of the program. This would take away tha advantage of
data hiding.
C++ provides a third visibility modifier, protected which serve a limit purpose in inheritance.
A member declared as protected is accessible by the member function within its class and any class
immediately derived from it . It cannot be accessed by the functions outside theirs two classes.
When a protected member is inherited in public mode it becomes protected to the derived class and
therefore is accessible by the member functions of the derived class. It is also ready for future inheritance
.
A protected member inherited in private mode, becomes private in the derived class. Although it is
available to the member functions of the derived class, it is not available for further inheritance (since
private members cannot be inherited).
It is also possible to inherit a base class in protected mode. In protected derivation, both public and
protected members of the base class become protected members to the derived class.
The keywords private, protected, public may appear in any order and any no.of times in the declaration
of the class. For example.
Class data
{
Protected:
--------
--------
public:
--------
--------
private:
--------
---------
public:
--------
---------
};
The table for the visibility of inherited members.
Base class derived cass visibility
Visibility public private protected
Derivation derivation derivation
Private not inherited not inherited not inherited
Public public private proteccted
Protected protected private protected
Multilevel inheritance:- It is non-uncommon (common) that a class is derived from another derived
class . The class A serves as a base class for the derived class B, which in term serves as a base class for
the derived class C. The class B is known as “Intremediate base class”, since it provides a link between A
and C. The chain ABC is known as Inheritance path.
Base path
A

Inherited Path. B Intermediate base class.


Derived class.
C

Let us consider a simple example. Assume the test result of a batch of students are stored in three
different classes class student stores the roll.no, class test stores the marks obtained in 2 subjects and class
result contains the total marks obtaimed in the test. The class result can inhert the details of marks
multilevel inheritance. The class result after inheritance would contain following members.
Program for multilevel inheritance.
#include < iostream.h>
#include< conio.h>
class student
{
protected : int roting;
Public : void get no( )
{
cout<< “\n enter your rollno”;
cin >> rollno:
}
cout<<”\n Roll no=” << roll no;
};
class test : public student
{
protected : int sub1; sub2;
public : void getmarks( )
{
cout<< “\n enter 2 subjects merks”;
cin >> sub1 >> sub2;
}
void putmarks( )
{
cout<< “\n marks 1 =” << sub1;
cout << “\n marks 2 =” << sub2;
}
};
class result : public test
{
private : int total;
public : void display( )
{
putno( );
putmarks( );
total= sub 1=sub 2;
cout<< “\n Total=” << total;
}
};
void main( )
{
result s;
clrscr( );
s.getno( );
s.getmarks( );
s.display( ); }
Multiple inheritance:- A class can inherit the attributes of two or more classes, is known as 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. It is represented as follows.

B1 B2 B3

C
----

The syntax of a derived class with multiple base classes is as follows.


Class C : visibility mode B1, visibility mode B2- - - -
{
body of c;
};
Where visibility mode may be either public or private. The base classes are represented by commas .
Example Program. To find out the student details using multiple inheritance.
#include<iostream.h>
#include<conio.h>

class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;

}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}

Output:

Enter the Roll no: 100

Enter two marks

90
80

Enter the Sports Mark: 90

Roll No: 100


Total : 260
Average: 86.66

Hierarchical inheritance:-
If the traits of one class may be inherited by more than one derived class is known as Hierarchical
inheritance .
Eg:- W.A.P. to show the vehicle database using Hierarchical inheritance.
The hierarchical inheritance for vehicle database is represented as.

Vehicle

car truck

Here the base class is vehicle , car and tuck are derived classes. They inherits the properties of the
vehicle.
Exsample Program:- In the Below program Class A is Base Class and Class B ,Class C ,Class D are
derived class.(As Per above Diagram)

#include<iostream.h>

#include<conio.h>

class A //Base Class


{
public:
int a,b;
void getnumber()
{
cout<<"\n\nEnter Number :::\t";
cin>>a;
}

};

class B : public A //Derived Class 1


{
public:
void square()
{
getnumber(); //Call Base class property
cout<<"\n\n\tSquare of the number :::\t"<<(a*a);
cout<<"\n\n\t----------------------------------------------------";
}
};

class C :public A //Derived Class 2


{
public:
void cube()
{
getnumber(); //Call Base class property
cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
cout<<"\n\n\t----------------------------------------------------";
}
};

int main()
{
clrscr();

B b1; //b1 is object of Derived class 1


b1.square(); //call member function of class B
C c1; //c1 is object of Derived class 2
c1.cube(); //call member function of class C
getch();
}
Hybrid inheritance:- There could be situations where we need to play apply two or more types of
inheritance to design a program. For example, consider the case of processing the student result as show
in the following figure.

Example programme: In the below program class B inherits property(member function) of class A
which is base class and class D inherits property
from class B and class

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

class A //Base class


{
public:
int l;
void len()
{
cout<<"\n\nLenght :::\t";
cin>>l; //Lenght is enter by user
}
};
class B :public A //Inherits property of class A
{
public:
int b,c;
void l_into_b()
{
len();
cout<<"\n\nBreadth :::\t";
cin>>b; //Breadth is enter by user
c=b*l; //c stores value of lenght * Breadth i.e. (l*b) .
}
};

class C
{
public:
int h;
void height()
{
cout<<"\n\nHeight :::\t";
cin>>h; //Height is enter by user
}
};

//Hybrid Inheritance Level


class D:public B,public C
{
public:
int res;
void result()
{
l_into_b();
height();
res=h*c; //res stores value of c*h where c=l*b and h is height which is enter by user
cout<<"\n\nResult (l*b*h) :::\t"<<res;
}
};

int main()
{
clrscr();
D d1;
d1.result();
getch();

Virtual Base class:- Consider a situation where all the three kinds of inheritance namely multilevel,
multiple and hierarchical inheritance are involved. This is illustrated as.

students

test sports

result

It shows that the result class has two direct base classes test and sports which
themselves have a common base class student. The result inherits the traits (properties) if students
via(though) of two separate line. The student class is sometimes referred as indirect base class.
Inheritance by the class result might pose some problems. All the public and protected members of
student class are inherited into result class thrice, first via test class and again via sports class. this means,
the result class would have duplicate sets of members inherited from base class student. This introduces
ambiguity and should be avoided.
The duplication of inherited members gave to their multiple path can be avoided by making the common
base class as “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, regard less of how many inheritance pass exist between virtual base class and a derived base
class.
Syntax:- class base class name
{
----
------
class deprival class name : visibility mode virtual Base class name.
{
------
------
};
The student class is considered as a virtual base and it is represented as follow.

students

test sports

result

#include <iostream.h>
class student
{
proteced : int r no;
public : void get no( )
{
cout <<\n enter your roll no”;
cin >> r no;
}
void put no( )
{
cout <<” roll number =” << r no;
}
};
class test : public virtual student
{
protected : int m1, m2, m3;
public : void get marks( );
{
cout<< “\n enter marks of 3 subjects”;
cin >> m1 >> m2 >> m3;
}
void putmarks( )
{
cout <<” maths = “<< m1;
cout <<” physics =” << m2;
cout <<” computers =” << m3;
}
};
class sports : public virtual student
{
protected : int score;
public : void getscore( )
{
cout<< “ enter the sports weightage”;
cin >> score;
}
void putsscore( )
{
cout <<” score =” << score;
}
};
class result : public test, public sports
{
private : int tot;
public : void getresult( )
{
putno( );
putmarks( );
putscore( );
tot = m1+ m2+m3+score;
cout <<” Total=” <<tot;
}
};
void main( )
{
result s;
clrscr( );
s.get no( );
s.getmarks( );
s.getscore( );
s.getresult( );
getch( );
}

C++ Pointers

ointers are the powerful feature of C++ programming which differs it from other popular programming
languages like: Java, Visual Basic etc.

To understand pointers, you should have the knowledge of address in computer memory. Computer
memory is broken down into bytes and each byte has its own address. For example: In 1KB memory,
there are 1024 bytes and each byte is given an address (0 - 1023).

The Address-of Operator &


The & operator can find address occupied by a variable. If var is a variable then, &var gives the address
of that variable.

Pointers Variables

Consider a normal variable as in above example, these variables holds data. But pointer variables or
simply pointers are the special types of variable that holds memory address instead of data.

How to declare a pointer?


int *p;
OR,
int* p;

The statement above defines a pointer variable p. The pointer p holds the memory address. The asterisk is
a dereference operator which means pointer to. Here pointer p is a pointer to int, that is, it is pointing an
integer.

Note: In above statement p is a pointer variable that holds address not *p. The *pis an expression. The
content(value) of the memory address pointer p holds is given by expression *p.
Example 2: C++ Pointers

C++ Program to demonstrate the working of pointer.

#include <iostream>
using namespace std;
int main() {
int *pc, c;

c = 5;
cout<< "Address of c (&c): " << &c << endl;
cout<< "Value of c (c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c


cout<< "Address that pointer pc holds (pc): "<< pc << endl;
cout<< "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

*pc = 2;
cout<< "Address of c (&c): "<< &c <<endl;
cout<<"Value of c (c): "<< c<<endl<< endl;

return 0;
}

Output

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 2

C++ Pointers and Arrays


Pointers are the variables that hold address. Pointers can point at cells of an array not only single variable.
Consider this example:
int* ptr;
int a[5];
ptr = &a[2]; // &a[2] is the address of third element of a[5].
Suppose, pointer needs to point to the fourth element of an array, that is, hold address of fourth array
element in above case. Since ptr points to the third element in the above example, ptr + 1 points to the
fourth element. You may think that, ptr + 1 may hold the address of byte next to ptr. But it's not correct. It
is because pointer ptr is a pointer to int and size of int is fixed for a operating system (size of int is 4 byte
of 64-bit operating system). Hence, the address between ptr and ptr + 1 differs by 4 bytes. If pointer ptr
was pointer to char then, the address between ptr and ptr + 1 would have differed by 1 byte since size of a
character is 1 byte.
Example 1:
C++ Program to display address of elements of an array using both array and pointers
#include <iostream>
using namespace std;

int main() {
float a[5];
float *ptr;

cout << "Displaying address using arrays: "<<endl;


for (int i = 0; i < 5; ++i) {
cout << "&a[" << i << "] = " << &a[i] <<endl;
}

ptr = a; // ptr = &a[0]


cout<<"\nDisplaying address using pointers: "<< endl;
for (int i = 0; i < 5; ++i) {
cout << "ptr + " << i << " = "<<ptr+i <<endl;
}

return 0;
}

C++ Virtual Function and Polymorphism

If there are member functions with same name in base class and derived class, virtual functions gives
programmer capability to call member function of different class by a same function call depending upon
different context. This feature in C++ programming is known as polymorphism which is one of the
important feature of OOP.

If a base class and derived class has same function and if you write code to access that function using
pointer of base class then, the function in the base class is executed even if, the object of derived class is
referenced with that pointer variable. This can be demonstrated by an example.

#include <iostream>
using namespace std;
class B
{
public:
void display()
{ cout<<"Content of base class.\n"; }
};
class D : public B
{
public:
void display()
{ cout<<"Content of derived class.\n"; }
};

int main()
{
B *b;
D d;
b->display();

b = &d; /* Address of object d in pointer variable */


b->display();
return 0;
}

Note: An object(either normal or pointer) of derived class is type compatible with pointer to base class.
So, b = &d; is allowed in above program.

Output

Content of base class.


Content of base class.

In above program, even if the object of derived class d is put in pointer to base class, display( ) of the
base class is executed( member function of the class that matches the type of pointer ).

Virtual Functions

If you want to execute the member function of derived class then, you can declare display( ) in the
base class virtual which makes that function existing in appearance only but, you can't call that function.
In order to make a function virtual, you have to add keyword virtual in front of a function.

/* Example to demonstrate the working of virtual function in C++ programming. */

#include <iostream>
using namespace std;
class B
{
public:
virtual void display() /* Virtual function */
{ cout<<"Content of base class.\n"; }
};

class D1 : public B
{
public:
void display()
{ cout<<"Content of first derived class.\n"; }
};

class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived class.\n"; }
};

int main()
{
B *b;
D1 d1;
D2 d2;

/* b->display(); // You cannot use this code here because the function of base class is virtual. */

b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */
return 0;
}

Output

Content of first derived class.


Content of second derived class.

After the function of base class is made virtual, code b->display( ) will call the display( ) of the
derived class depending upon the content of pointer.

In this program, display( ) function of two different classes are called with same code which is one of
the example of polymorphism in C++ programming using virtual functions.

C++ Abstract class and Pure virtual Function

In C++ programming, sometimes inheritance is used only for the better visualization of data and you do
not need to create any object of base class. For example: If you want to calculate area of different objects
like: circle and square then, you can inherit these classes from a shape because it helps to visualize the
problem but, you do not need to create any object of shape. In such case, you can declare shape as a
abstract class. If you try to create object of a abstract class, compiler shows error.
Declaration of a Abstract Class
If expression =0 is added to a virtual function then, that function is becomes pure virtual function. Note
that, adding =0 to virtual function does not assign value, it simply indicates the virtual function is a pure
function. If a base class contains at least one virtual function then, that class is known as abstract class.

Example to Demonstrate the Use of Abstract class

#include <iostream>
using namespace std;

class Shape /* Abstract class */


{
protected:
float l;
public:
void get_data() /* Note: this function is not virtual. */
{
cin>>l;
}

virtual float area() = 0; /* Pure virtual function */


};

class Square : public Shape


{
public:
float area()
{ return l*l; }
};

class Circle : public Shape


{
public:
float area()
{ return 3.14*l*l; }
};

int main()
{
Square s;
Circle c;
cout<<"Enter length to calculate area of a square: ";
s.get_data();
cout<<"Area of square: "<<s.area();
cout<<"\nEnter radius to calcuate area of a circle:";
c.get_data();
cout<<"Area of circle: "<<c.area();
return 0;
}

In this program, pure virtual function virtual float area() = 0; is defined inside class Shape, so this
class is an abstract class and you cannot create object of class Shape

You might also like