C++ Notes
C++ Notes
INTRODUCTION TO C++
C++ is an object-oriented programming language and is considered to be an extension of C.
Bjarne Stroustrup at AT&T Bell Laboratories; Murray Hill, New Jersey (USA) developed it
in the early eighties of twentieth century.
Stroustrup, a master of Simula67 and C, wanted to combine the features of both the
languages into a more powerful language that could support object-oriented programming
with features of C. The outcome was C++ as per in the following figure.
Various ideas were derived from SIMULA67 and ALGOL68. Stroustrup called the new
language ‘C with classes’. However, in 1983, the name was changed to C++. The thought of
C++ came from the C increment operator ++.
Rick Mascitti coined the term C++ in 1983. Therefore, C++ is an extended version of C. C++
is a superset of C. All the concepts of C are applicable to C++ also.
For developing complicated applications object-oriented languages are most convenient and
easy. Hence, a programmer must be aware of the new concepts of object-oriented techniques.
A C++ program is a collection of commands, which tell the computer to do "something".
collection of commands is usually called C++ source code, source code or just code.
Commands are either "functions" or "keywords". Keywords are a basic building block of the
language, while functions are, in fact, usually written in terms of simpler functions.
OBJECT-ORIENTED PROGRAMMING
Object-oriented programming language is a feature that allows a mode of modularizing
programs by forming separate memory area for data as well as functions that is used as object
for making copies of modules as per requirement.
Object Oriented Programming and C++
Fig.Evolution of C++
Objects
Objects are primary run-time entities in an object-oriented programming. Objects are primary
run-time entities in an object-oriented programming.
They may stand for a thing that has specific application for example, a spot, a person, any
data item related to program, including user-defined data types. Programming issues are
analyzed in terms of object and the type of transmission between them.
The selected program objects must be similar to actual world objects. Objects occupy space
in memory. Every object has its own properties or features.
An object is a specimen of a class. It can be singly recognized by its name. It declares the
state shown by the data values of its characteristic at a specific time.
The state of the object varies according to procedure used. It is known as the action of the
object. The action of the object depends upon the member function defined within its class.
Fig.Examples of Objects
Classes are an expanded concept of data structures: like data structures, they can contain
data members, but they can also contain functions as members.
Object Oriented Programming and C++
An object is an instantiation of a class. In terms of variables, a class would be the type, and
an object would be the variable.
Classes are defined using either keyword class or keyword struct, with the following syntax:
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
}object_names;
class_name is a valid identifier for the class, object names is an optional list of names for
objects of this class. The body of the declaration can contain members, which can either be
data or function declarations, and optionally access specifiers.
The format is the same as for plain data structures, except that they can also include
functions, and have this new things called access specifiers. An access specifier is one of
the following three keywords: private, public or protected. These specifiers modify the
access rights for the members that follow them:
private members of a class are accessible only from within other members of the same class
(or from their "friends").
protected members are accessible from other members of the same class (or from their
"friends"), but also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for
all its members. Therefore, any member that is declared before any other access specifier has
private access automatically. For example:
class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area (void);
} rect;
Declares a class (i.e., a type) called Rectangle and an object (i.e., a variable) of this class,
called rect.
This class contains four members: two data members of type int (member width and member
height) with private access (because private is the default access level) and two member
functions with public access: the functions set_values and area, of which for now we have
only included their declaration, but not their definition.
Notice the difference between the class name and the object name: In the previous example,
Rectangle was the class name (i.e., the type), whereas rect was an object of type Rectangle. It
is the same relationship int and a have in the following declaration:
o Int a;
where int is the type name (the class) and a is the variable name (the object).
After the declarations of Rectangle and rect, any of the public members of object rect can
o be accessed as if they were normal functions or normal variables, by simply inserting
a
dot (.) between object name and member name. This follows the same syntax as accessing
the members of plain data structures.
Object Oriented Programming and C++
A class provides the blueprints for objects, so basically an object is created from a class. We
declare objects of a class with exactly the same sort of declaration that we declare variables
of basic types. Following statements declare two objects of class Box:
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.
For example:
rect.set_values (3,4);
myarea = rect.area();
The only members of rect that cannot be accessed from outside the class are width and height,
since they have private access and they can only be referred to from within other members of
that same class.
Here is the complete example of class Rectangle:
// classes example
#include <iostream>
using namespace std;
class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main ()
{
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
This example reintroduces the scope operator (::, two colons), seen in earlier chapters in
relation to namespaces. Here it is used in the definition of function set values to define a
member of a class outside the class itself.
Notice that the definition of the member function area has been included directly within the
definition of class Rectangle given its extreme simplicity. Conversely, set_values it is merely
declared with its prototype within the class, but its definition is outside it. In this outside
definition, the operator of scope (::) is used to specify that the function being defined is a
member of the class Rectangle and not a regular non-member function.
The scope operator (::) specifies the class to which the member being declared belongs,
granting exactly the same scope properties as if this function definition was directly included
within the class definition. For example, the function set_values in the previous example has
access to the variables width and height, which are private members of class Rectangle, and
thus only accessible from other members of the class, such as this.
The only difference between defining a member function completely within the class definition
or to just include its declaration in the function and define it later outside the class, is that in the
first case the function is automatically considered an inline member function by the compiler,
while in the second it is a normal (not-inline) class member function. This causes no
differences in behavior, but only on possible compiler optimizations.
Object Oriented Programming and C++
Members width and height have private access (remember that if nothing else is specified,
all members of a class defined with keyword class have private access). By declaring them
private, access from outside the class is not allowed. This makes sense, since we have already
defined a member function to set values for those members within the object: the member
function set_values. Therefore, the rest of the program does not need to have direct access to
them. Perhaps in a so simple example as this, it is difficult to see how restricting access to these
variables may be useful, but in greater projects it may be very important that values cannot be
modified in an unexpected way (unexpected from the point of view of the object).
A class is grouping of objects having identical properties, common behavior, and shared
relationship. A class is the accomplishment of abstract data type.
It defines the nature and methods that act on the data structure and abstract data type
respectively. Specimens are also known as objects. In other words, a class is a grouping of
objects having identical properties, common behavior, and shared relationship.
The entire group of data and code of an object can be built as a user-defined data type using
class. Objects are nothing but variables of type class.
Once a class has been declared, the programmer can create a number of objects associated
with that class. The syntax used to create an object is similar to the syntax used to create an
integer variable in C.
A class is a model of the object. Every object has its own value for each of its member
variables.
However, it shares the property names or operations with other instances of the class. Thus,
classes define the characteristics and actions of different objects.
Method
An operation required for an object or entity when coded in a class is called a method. An
operation required for an object or entity when coded in a class is called a method.
The operations that are required for an object are to be defined in a class. All objects in a
class perform certain common actions or operations.
Each action needs an object that becomes a function of the class that defines it and is referred
to as a method.
Object Oriented Programming and C++
The class, its associated data members, and functions are shown in different styles. This style
is frequently used while writing a class in the program
The class A contains private data members and public methods or member functions.
Generally, the data members are declared private, and member functions are declared public.
We can also define public data members and private member functions.
The data member of any class uses its member functions or methods to perform operations.
A series of operation steps may develop a set of messages between these objects. Each object
shows its own attributes.
Encapsulation
Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse. Data encapsulation led to the important OOP concept of data hiding
Data encapsulation is a mechanism of bundling the data, and the functions that use them
and data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. We already have studied that a class can contain private,
protected and public members. By default, all items defined in a class are private.
For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed
only by other members of the Box class, and not by any other part of your program. This is one
way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must
declare them after the public keyword. All variables or functions defined after the public
specifier are accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all other
classes as possible.
The packing of data and functions into a single component is known as encapsulation.
C++ supports the features of encapsulation using classes. The packing of data and functions
into a single component is known as encapsulation. The data is not accessible by outside
functions.
Only those functions that are able to access the data are defined within the class. These
functions prepare the interface between the object's data and the program. With
encapsulation data hiding can be accomplished.
Data hiding is an important feature. By data hiding an object can be used by the user without
knowing how it works internally.
The goal of the class is to encapsulate complication. The class also has mechanism for
hiding the data. Each member in the class may be private or public. Any non-member
function cannot access the data of the class.
The public section of the class must be carefully coded not to expose the inner details of the
class.
Object Oriented Programming and C++
class. The private member total is something that is hidden from the outside world, but is needed
for the class to operate proper.
Inheritance
Inheritance is the method by which objects of one class get the properties of objects of
another class.
Inheritance is the method by which objects of one class get the properties of objects of
another class. In object-oriented programming, inheritance provides the thought of
reusability. The programmer can add new properties to the existing class without changing it.
Inheritance
This can be achieved by deriving a new class from the existing one. The new class will
possess features of both the classes. The actual power of inheritance is that it permits the
programmer to reuse a class that is close to what he wants, and to tailor the class in such a
manner that it does not bring any unwanted incidental result into the rest of the class.
Thus, inheritance is the feature that permits the reuse of an existing class to make a new
class.
In the figure red, yellow and blue are the main colours. Orange colour is created from the
combination of red and yellow, green is created from yellow and blue, and violet is created
from red and blue.
Orange colour has attributes of both red and yellow, which produces a new effect. Thus,
many combinations are possible.
Polymorphism
Polymorphism allows the same function to act differently in different classes. Polymorphism
makes possible the same functions to act differently on different classes as shown in Figure.
It is an important feature of OOP concept and has the ability to take more than one form.
Polymorphism accomplishes an important part in allowing objects of different classes to
share the same external interface. It is possible to code a non-specific (generic) interface to a
set of associated actions.
Object Oriented Programming and C++
Polymorphism in OOP
Dynamic Binding
Binding means connecting one program to another program that is to be executed in reply to
the call. Binding means connecting one program to another program that is to be executed in
reply to the call. Dynamic binding is also known as late binding.
The code present in the specified program is unknown till it is executed. It is analogous to
inheritance and polymorphism.
In Figure, polymorphism allows single object to invoke similar function from different
classes. The program action is different in all the classes. During execution time, the code
analogous to the object under present reference will be executed.
Message Passing
Object-oriented programming includes objects which communicate with each other.
Programming with these objects should be followed in steps shown below:
(1) Declaring classes that define objects and their actions.
(2) Declaring objects from classes.
(3) Implementing relation between objects.
Message passing
Data is transferred from one object to another. A message for an object is the demand for
implementation of the process. Message passing contains indicating the name of the object,
function, and required data elements.
Objects can be created, released, and interacted with each other. An object is workable, as
long as it is active. In object-oriented programming, there is a panorama of independent
objects that communicate with each other by swapping messages.
Objects invoke member functions. They also negate if the calling object is not a member of
the same class. Thus a message is a solicitation to an object to call one of its member
functions.
A message contains name of the member function and parameters of the function. Execution
of member function is just a response generated due to receipt of a message. It is possible
when the function and the object are of the same class.
Reusability
Object-oriented technology allows reusability of the classes by extending them to other
classes using inheritance. Object-oriented technology allows reusability of classes by
extending them to other classes using inheritance.
Object Oriented Programming and C++
Once a class is defined, the other programmer can also use it in their programs and add new
features to the derived classes. Once verified the qualities of base classes need not be
redefined. Thus, reusability saves time.
Class A is reused and class B is created. Again class B is reused and class C is created.
Delegation
In OOP, two classes can be joined either by - inheritance or delegation, which provide
reusability of the class.
In inheritance, one class can be derived from other class and relationship between them is
known as kind of relationship. For example, if class Y is derived from class X, then class Y
is known as kind of X.
The second type of relationship is has a relationship. When object of one class is used as
data member in other class, such composition of objects is known as delegation.
Class C has two data members that are objects of class A and B. Such a relationship between
two classes is known as has a relationship.
Genericity
The software components of a program have more than one version depending on the data
types of arguments. This feature allows declaration of variables without specifying exact data
type.
The compiler identifies the data type at run-time. The programmer can create a function that
can be used for any type of data. The template feature in C++ allows generic programming.
ADVANTAGES OF OOPS
Object-oriented programming provides many advantages to the programmer and the user.
This technology solves many problems related to software development, provides improved
quality, and low cost software. OOP has the following advantages:
(1) Object-oriented programs can be comfortably upgraded.
(2) Using inheritance, redundant program codes can be eliminated and the use of previously
defined classes may be continued.
(3) The technology of data hiding facilitates the programmer to design and develop safe
programs that do not disturb code in other parts of the program.
(4) The encapsulation feature provided by OOP languages allows programmer to define the
class with many functions and characteristics and only few functions are exposed to the
user.
(5) All object-oriented programming languages can create extended and reusable parts of
programs.
(6) Object-oriented programming enhances the thought process of a programmer leading to
rapid development of new software in short span of time.
Object Oriented Programming and C++
OBJECT-ORIENTED LANGUAGES
There are many languages which support object-oriented programming. Following object-
oriented languages are widely accepted by the programmer:
C++
SmallTalk
Charm++
Java
C++
SMALLTALK
Smalltalk is purely an object-oriented programming language. C++ makes few compromises
to ensure quick performance and small code size.
Smalltalk uses run-time binding. Smalltalk programs are considered to be faster than C++
and needs longer time to learn. Smalltalk programs are written using Smalltalk browser.
Smalltalk uses dynamic objects and memory is allocated from free store.
It also provides automatic garbage collection and memory is released when object is no
longer in use.
CHARM++
Charm ++ is also an object-oriented programming language. It is portative. The language
provides features such as inheritance, strict type checking, overloading, and reusability.
It is designed in order to work efficiently with different parallel systems, together with shared
memory systems and networking.
Object Oriented Programming and C++
JAVA
Java was developed by Patrick Naughton, James Gosling, Chris Warth, Mike Sheridan, and
Ed Frank at Sun Microsystems.
Java is an object-oriented programming language and supports maximum OOP
characteristics.
Its statement structure is like C and C++, but it is easier than C++. Java excludes few
confusing and unsafe features of C and C++, for example, pointers.
Java allows client/server programming and is used for Internet programming. The Java
programs are downloaded by the client machines and executed on different types of
hardware. This portability is achieved by translation of Java program to machine code using
compiler and interpreter.
The Java compiler converts the source program to JVM (Java virtual machine). The JVM is a
dummy CPU. The compiler Java program is known as byte code. The Java interpreter
translates byte code into object code. Compiler and interpreter do the conversion of Java
program to object code.
STREAMS IN C++
C++ supports a number of Input/output (I/O) operations to read and write operations. These
C++ I/O functions make it possible for the user to work with different types of devices such
as keyboard, disk, tape drivers etc.
The stream is an intermediator between I/O devices and the user. The standard C++ library
contains the I/O stream functions. The I/O functions are part of the standard library that
provides portability to the language itself.
A library is nothing but a set of .obj files. It is connected to the user's program. Stream is
flow of data in bytes in sequence.
If data is received from input devices in sequence then it is called as source stream and when
the data is passed to output devices then it is called as destination stream. It is also referred
as encapsulation through streams.
The data is received from keyboard or disk and can be passed on to monitor or to the disk.
Figure describes the concept of stream with input and output devices.
Object Oriented Programming and C++
Data in source stream can be used as input data by program. So the source stream is also
called as input stream. The destination stream that collects output data from the program
is known as output stream. The mechanism of input and output stream is illustrated in the
following figure.
Thus, the stream acts as an intermediator or interface between I/O devices and the user.
The input stream pulls the data from keyword or storage devices such as hard disk, floppy
disk etc.
The data present in output stream is passed on to the output devices such as monitor,
printer etc.
PRE-DEFINED STREAMS
C++ has a number of pre-defined streams. These pre-defined streams are also called as
standard I/O objects.
These streams are automatically activated when the program execution starts. Predefined
C++ stream or I/O global objects
BUFFERING
Buffer
It is a block of memory used to hold data temporarily. It is always located between a
peripheral device and faster computer. Buffers are used to pass data between computer and
devices.
The buffer increases the performance of the computer by allowing read/write operation in
larger chunks. For example, if the size of buffer is N, the buffer can hold N number of bytes
of data.
Writing data to the disk is very costly. The read/write operation with disk takes a long time.
While these operations are carried out the execution of the program will be slow for few
seconds.
If the program involves a lot of read and write operations, the program execution speed will
be slower. To avoid this problem the stream provides buffer. Buffer holds the data
temporarily. The input data is passed on to the stream buffer.
The data is not written to the disk immediately till the buffer fills. When the buffer is
completely filled the data is written on to the disk.
Object Oriented Programming and C++
STREAM CLASSES
C++ streams are based on class and object theory. C++ has a number of stream classes that
are used to work with console and file operations.
These classes are known as stream classes.
All these classes are declared in the header file iostream.h.
The file iostream.h must be included in the program if we are using functions of these
classes.
As described in Figure the classes istream and ostream are derived classes of base class ios.
The ios class contains member variable object streambuf.v.
The streambuf places the buffer. The member function of streambuf class handles the buffer
by providing the facilities to flush clear and pour the buffer.
The class iostream is derived from the classes istream and ostream by using multiple
inheritance. The ios class is a virtual class and this is to avoid ambiguity that frequently
appears in multiple inheritances.
The ios class has an ability to handle formatted and unformatted I/O operations.
The istream class gives support to both formatted and unformatted data. The Os t ream
classes handle the formatting of output of data.
The ios tream contains functioning of both is istream and ostream classes.
INPUT STREAM
The input stream does read operation through keyboard.
It uses cin as object. The cin statement uses >> (extraction operator) before variable name.
The cin statement is used to read data through the input device. Its syntax and example are as
follows.
Syntax:
Cin>> variable;
Write a program to accept string through the keyboard and display it on the screen.Use cin
and cout statements.
#include<iostream.h>
#include<conio.h>
Void main()
{
char name[15];
clrscr();
cout<<”Enter your name”;
cin<<name
cout<<”Your name is”<<name;
Return 0;
}
OUTPUT
Enter your name:Asha
Your name is:Asha
Object Oriented Programming and C++
Function Working
To set the required field width. The output will be displayed in given
Width()
width.
Precision () To set number of decimal point for a float value.
BIT FIELDS
The ios class contains the setf( ) member function. The flag indicates the format design.
The syntax of the unsetf( ) function is used to clear the flags. The syntaxes of function are as
follows.
Syntax: cout.setf(v1, v2);
Syntax: cout.unsetf(v1);
where, variable v1 and v2 are two flags. Table describes the flag and bit-field setting that
can be used with this function. The unsetf( ) accepts setting of v1 and v2 arguments.
Object Oriented Programming and C++
MANIPULATORS
The output formats can be controlled using manipulators. The header file iomanip.h has a set
of functions. Effect of these manipulators is the same as ios class member functions. Every ios
member function has two formats. One is used for setting and second format is used to know the
previous setting. But the manipulator does not return to the previous setting. The manipulator can
be used with cout( ) statement as given below.
Here m1 and m2 are two manipulators and v1 is any valid C++ variable.
The table describes the most useful manipulators. The manipulator hex, dec, oct, ws, endl,
and flush are defined in iostream.h. The manipulator setbase, width( ), fill( ) etc. that requires an
argument are defined in iomanip.h.
Table:Manipulators
Manipluators Function
USER-DEFINED MANIPULATORS
The programmer can also define his/her own manipulator according to the requirements
of the program. The syntax for defining manipulator is given below:
ostream & m_name( ostream & o )
{
statement1;
statement2;
return o;
}
The m_name is the name of the manipulator.
Write a program to create manipulator equivalent to ‘\t’. Use it in the program and format
the output.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
ostream & tab (ostream & o)
{
o <<"\t";
Object Oriented Programming and C++
return o;
}
void main( )
{
clrscr( );
cout <<1<<tab<<2 <<tab<<3;
}
OUTPUT
123
Explanation: illustrates working of the program.
In the above program, tab named manipulator is defined. The definition of tab manipulator
contains the escape sequence ‘\t’. Whenever we call the tab manipulator, the ‘\t’ is executed and
we get the effect of tab.
MANIPULATOR WITH ONE PARAMETER
The prototype declared in the iomanip.h as described earlier allows us to define
individual set of macros. The manipulator can be created without the use of int or long
arguments.
Write a program with one parameter to display the string in the middle of the line.
# include <iostream.h>
# include <iomanip.h>
# include <string.h>
# include <conio.h>
ostream& fc (ostream& ost, int iw)
{
for (int k=0;k<((75-iw)/2);k++)
ost <<" ";
return (ost);
}
OMANIP (int) middle (int iw)
{
return OMANIP (int) (fc,iw);
}
int main( )
{
clrscr( );
char *m=" * Well come *";
Object Oriented Programming and C++
C++ DECLARATIONS
INTRODUCTION
Before writing any program it is necessary to know the rules of syntaxes of the language. This
enables a programmer to write error-free programs. The user makes many mistakes if he/she
does not know the rules of the language even though the logic is clear. Thus the user fails to
write programs due to poor knowledge of basic concepts.
Some basic concepts of C++ language are illustrated in this chapter to help the programmer
develop the programs. As object-oriented programming is a new technology, the programmer
will find a notable amount of new concepts to learn and master in it. This chapter explores
syntaxes, data types, keywords etc.
Most of the C++ programmers are former C programmers. Some rules and regulations of C
programs are valid in C++ also. In fact C++ is upward compatible to C. Hence the programs with
C can be executed with C++. In C++, various improvements are done such as variable
declaration is allowed anywhere in the program, new operators such as reference, scope access
operator etc. are introduced and so on. All these concepts are illustrated ahead with figures and
examples.
TYPES OF TOKENS
The C++ programs contain various components. The compiler identifies them as tokens.
Tokens are classified in the following types.
(a) Keywords
(b) Variables
(c) Constants
(d) Special character
(e) Operators
Fig.Types of Tokens
The keywords are reserved set of words with fixed meanings. The variables are used to
hold data temporarily. The operators are used to perform different operations such as arithmetic,
logical etc. The values such as 1, 5, 2.5 etc. are known as constants. The operators such as #, and
~ are known as special characters. The # is used for preprocessor directive? is a conditional
operator and ~ is used for bitwise operation. The detailed descriptions of these tokens are
described in sections ahead.
Object Oriented Programming and C++
KEYWORDS
The C++ keywords are reserved words by the compiler and have fixed meanings. All C
keywords are valid in C++. There are 63 keywords in C++. In addition, Turbo C++ permits 14
extra keywords as described. The programmer may not apply them in the programs for defining
variable names. However, few C++ compilers permit to declare variable names that exactly
match to the keywords.
The common keywords between C and C++ are listed in Table.1.Table.2 describes the
additional keywords of C++. These keywords are used with classes, templates, and exception
handling etc. Table.3 contains keywords added by the ANSI committee
asm private
catch protected
class public
delete template
friend this
inline throw
new try
operator virtual
IDENTIFIERS
Identifiers are names of variables, functions, and arrays etc. They are user-defined names,
consisting of a sequence of letters and digits, with a letter as a first character. Lower case letters
are preferred. However, the upper case letters are also permitted. The (_) underscore symbol can
be used as an identifier. In general, underscore is used to link two words in long identifiers.
ANSI C++ restricts no bound on length of variables.
DYNAMIC INITIALIZATION
Object Oriented Programming and C++
The declaration and initialization of variable in a single statement at any place in the program
is called as dynamic initialization. The dynamic initialization is always accomplished at run-time
i.e., when program execution is in action. Dynamic means process carried out at run-time, for
example, dynamic initialization, dynamic memory allocation etc. The C++ compiler allows
declaration and initialization of variables at any place in the program. In C, initialization of
variables can be done at any place but the variable must be declared at the beginning of the
program as illustrated in the following program:
Write a program in C to demonstrate declaration and initialization of a variable.
# include <conio.h>
# include <stdio.h>
void main( )
{
int r;
float area;
clrscr( );
printf ("\n Enter radius : ");
scanf ("%d",&r);
area=3.14*r*r;
printf ("\n Area =%g",area);
}
Write a program in C++ to demonstrate declaration and initialization of a variable
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}
Write a program in C++ which will produce correct size of various data types
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
Object Oriented Programming and C++
This example uses endl, which inserts a new-line character after every line and <<
operator is being used to pass multiple values out to the screen. We are also using sizeof()
function to get size of various data types.
When the above code is compiled and executed, it produces the following result which
can vary from machine to machine:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
2.Write a program in C++ which will produce a sample Boolean tests with bool, true, and
false.
#include <iostream>
using namespace std;
// non main function but just another function...
bool func()
{
// function returns a bool type
return NULL;
// NULL is converted to Boolean false, same
// as statement 'return false;'
}
int main()
{
bool val = false; // Boolean variable
int i = 1; // i is neither Boolean-true nor Boolean-false
int g = 5;
float j = 3.02; // j is neither Boolean-true nor Boolean-false
cout<<"Given the test value: "<<endl;
cout<<"bool val = false "<<endl;
cout<<"int i = 1 "<<endl;
cout<<"int g = 5 "<<endl;
cout<<"float j = 3.02 "<<endl;
cout<<"\nTESTING\n";
// tests on integers
if(i == true)
cout<<"True: value i is 1"<<endl;
if(i == false)
cout<<"False: value i is 0"<<endl;
if(g)\
cout << "g is true."<<endl;
else
cout << "g is false."<<endl;
cout<<"Boolean j is true."<<endl;
// test the Boolean function returns value
val = func();
if(val == false)
cout<<"func() returned false."<<endl;
if(val == true)
cout<<"func() returned true."<<endl;
// false is converted to 0
return false;
}
Output:
Output:
Object Oriented Programming and C++
Pointers
A pointer is a memory variable that stores a memory address. Pointer can have any name that
is legal for other variable and it is declared in the same fashion like other variable but it is always
denoted by ‘*’ operator.
int *x;
float *f;
char *y;
In the first statement ‘x’ is an integer pointer and it tells to the compiler that it holds the
address of any integer variable. In the same way f is a float pointer that stores the address of
any float variable and ‘y’ is a character pointer that stores the address of any character variable.
For a C++ program, the memory of a computer is like a succession of memory cells, each one
byte in size, and each with a unique address. These single-byte memory cells are ordered in a
way that allows data representations larger than one byte to occupy memory cells that have
consecutive addresses.
This way, each cell can be easily located in the memory by means of its unique address. For
example, the memory cell with the address 1776 always follows immediately after the cell with
address 1775 and precedes the one with 1777, and is exactly one thousand cells after 776 and
exactly one thousand cells before 2776.
When a variable is declared, the memory needed to store its value is assigned a specific
location in memory (its memory address). Generally, C++ programs do not actively decide the
exact memory addresses where its variables are stored. Fortunately, that task is left to the
Object Oriented Programming and C++
environment where the program is run - generally, an operating system that decides the particular
memory locations on runtime. However, it may be useful for a program to be able to obtain the
address of a variable during runtime in order to access data cells that are at a certain position
relative to it.
myvar = 25;
foo = &myvar;
bar = myvar;
The values contained in each variable after the execution of this are shown in the following
diagram:
First, we have assigned the value 25 to myvar (a variable whose address in memory we
assumed to be 1776).
The second statement assigns foo the address of myvar, which we have assumed to be 1776.
Finally, the third statement, assigns the value contained in myvar to bar. This is a standard
assignment operation, as already done many times in earlier chapters.
The main difference between the second and third statements is the appearance of the
reference operator (&).
The variable that stores the address of another variable (like foo in the previous example) is
what in C++ is called a pointer. Pointers are a very powerful feature of the language that has
many uses in lower level programming. A bit later, we will see how to declare and use
pointers.
Object Oriented Programming and C++
It is important to clearly differentiate that foo refers to the value 1776, while *foo (with an
asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is
25. Notice the difference of including or not including the dereference operator (I have added an
explanatory comment of how each of these two expressions could be read):
TYPE MODIFIERS
The keywords signed, unsigned, short, and long are type modifiers. A type modifier changes
the meaning of the base data type to produce a new data type. Each of these type modifiers is
applicable to the base type int. The modifiers signed and unsigned are also applicable to the base
type char. In addition, slong can be applied to double data type. When the base type is absent
from a declaration, int is supposed.
Examples:
long l; // int is implied
unsigned char c;
signed int s; // signed is default
unsigned long int u; // int OK, not necessary
Object Oriented Programming and C++
Write a program to declare variable with type modifiers, initialize them and display their
contents.
# include <conio.h>
# include <iostream.h>
void main( )
{
clrscr( );
short t=1;
long k=54111;
unsigned u=10;
signed j=-10;
cout <<"\n t="<<t;
cout <<"\n k="<<k;
cout <<"\n u="<<u;
cout <<"\n j="<<j;
}
Write a program to understand the difference between the way that signed and unsigned
integer modifiers are interpreted by C++
#include <iostream>
using namespace std;
/* This program shows the difference between
* signed and unsigned integers.
*/
int main()
{
short int i; // a signed short integer
short unsigned int j; // an unsigned short integer
j = 50000;
i = j;
cout << i << " " << j;
return 0;
}
When this program is run, following is the output:
-15536 50000
The above result is because the bit pattern that represents 50,000 as a short unsigned integer is
interpreted as -15,536 by a short.
WRAPPING AROUND
When a variable contains a value, which goes over the range provided by compiler, the
compiler won't flag any error in such cases and wrapping around takes places. For example, the
range of unsigned integer is 0 to 65535. Negative values and values greater than 65535 are not
permitted. If the variable of this type is assigned a value that is not in the above range, wrapping
takes place.
Unsigned int x=65536;
In the above statement, the unsigned variable x is assigned a value 65536 which is greater by
one than the range. In this case, difference between assigned value and total numbers that comes
under range are considered. For example, the total number that comes under this range is 65536
(0 to 65535). The value assigned is 65536. The difference is zero (65536-65536). The x contains
0. The same rule is applied to all other basic data type.
Object Oriented Programming and C++
TYPECASTING
C/C++ supports data types such as integer, character, floating, double precision, floating
point etc. Some of them are specified as int, short int, and long int. Typecasting is essential when
the values of variables are to be converted from one type to another type. C++ allows implicit as
well as explicit type conversion.
(1) Explicit Typecasting
Sometimes errors may be encountered in the program while using implicit typecasting. It is
preferred to use explicit type conversion process. The desired type can be achieved by
typecasting a value of particular type. The explicit type conversion is done using typecast
operator. The compiler is instructed to do type conversion using typecast operator. The following
are the syntaxes of typecasting in C and C++.
(2) Implicit Typecasting
Implicit conversions are automatically performed when a value is copied to a compatible
type. For example:
short a=2000;
int b;
b=a;
Here, the value of a is promoted from short to int without the need of any explicit operator.
This is known as a standard conversion. Standard conversions affect fundamental data types,
and allow the conversions between numerical types (short to int, int to float, double to int...), to
or from bool, and some pointer conversions.
Converting to int from some smaller integer type, or to double from float is known as
promotion, and is guaranteed to produce the exact same value in the destination type. Other
conversions between arithmetic types may not always be able to represent the same value
exactly:
If a negative integer value is converted to an unsigned type, the resulting value corresponds
to its 2's complement bitwise representation (i.e., -1 becomes the largest value representable
by the type, -2 the second largest, ...).
The conversions from/to bool consider false equivalent to zero (for numeric types) and to
null pointer (for pointer types); true is equivalent to all other values and is converted to the
equivalent of 1.
If the conversion is from a floating-point type to an integer type, the value is truncated (the
decimal part is removed). If the result lies outside the range of representable values by the
type, the conversion causes undefined behavior.
Otherwise, if the conversion is between numeric types of the same kind (integer-to-integer or
floating-to-floating), the conversion is valid, but the value is implementation-specific (and
may not be portable)
CONSTANTS
The constants in C++ are applicable to the values which do not change during execution of a
program. C++ supports various types of constants including integers, characters, floating, and
string constants. C++ has two types of constants; literal and symbolic.
Literal Constant
A literal constant is directly assigned to a variable.
Consider the following example:
int x=5;
where x is a variable of type int and 5 is a literal constant. We cannot use 5 to store another
integer value and its value cannot be altered. The literal constant doesn't hold memory location.
Object Oriented Programming and C++
CONSTANT POINTERS
C++ allows us to create constant pointer and also pointer to constant. Consider the following
example:
(1) Constant Pointer
It is not possible to modify the address of the constant pointer.
char * const str=”Constant”;
In the above example, it is not possible to modify the address of the pointer str. Thus, the
operations like the following will generate error:
// str="san"; // cannot modify a constant object
// ++str; // cannot modify a constant object
The following program won't work and will generate error message “cannot modify a
constant object”.
# include <iostream.h>
# include <constream.h>
void main( )
{
clrscr( );
char * const str="Constant";
str="new constant";
cout <<str;
}
int x=5;
++x;
In the above example the operator ++ is an increment operator. This operator adds one to the
value of operand. The different types of operators with their symbols are described in Table.
Fig.Types of operators
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is :31
Line 2 - Value of c is :11
Line 3 - Value of c is :210
Line 4 - Value of c is :2
Line 5 - Value of c is :1
Line 6 - Value of c is :21
if( a == b )
{
cout << "Line 1 - a is equal to b" << endl ;
}
else
{
Object Oriented Programming and C++
c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;
c = ~a; // -61 = 1100 0011
cout << "Line 4 - Value of c is: " << c << endl ;
c = a << 2; // 240 = 1111 0000
cout << "Line 5 - Value of c is: " << c << endl ;
c = a >> 2; // 15 = 0000 1111
cout << "Line 6 - Value of c is: " << c << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15
Here, qty is already declared and initialized. The second statement defines an alternative
variable name i.e., qt to variable qty. If both printed variables display the same value, any change
made in one of the variable causes change in both the variables.
COMMA OPERATOR
In C, every statement of the program is terminated by semi-colon (;). It is also applicable in
C++ and in addition, C++ allows us to terminate a statement using comma operator after
satisfying the following rules:
The variable declaration statements should be terminated by semi-colon.
The statements followed by declaration statements like clrscr( ), cin, cout can be
terminated by comma operator.
C++ permits declaration of variables at any place in program but such declaration is not
allowed in between the statements terminated by comma operator. The initialization of
previously declared variables can be done.
Object Oriented Programming and C++
CONTROL STRUCTURES
A Program is nothing but a set of statements written in sequential order, one after the other.
These statements are executed one after the other. Sometimes it may happen that the programmer
requires to alter the flow of execution, or to perform the same operation for fixed iterations or
whenever the condition does not satisfy. In such a situation the programmer uses the control
structure. There are various control structures supported by C++. Programs which use such (one
or three) control structures are said to be structured programs.
DECISION-MAKING STATEMENTS
Following are decision-making statements.
(1) The if statement
(2) The switch ( ) case statement.
Simple if statement
The syntax of simple if statement is described below
Syntax
For the simplest if statement:
if(expression) /*no semi-colon */
Statement;
Object Oriented Programming and C++
The if statement contains an expression. The expression is evaluated. If the expression is true
it returns 1 otherwise 0. The value 1 or any non-zero value is considered as true and 0 as false. In
C++, the values (1) true and (0) false are known as bool type data.
The bool type data occupies one byte in memory. If the given expression in the if( ) statement
is true, the following statement or block of statements too are executed, otherwise the statement
that appears immediately after if block (true block) is executed.
{
statement 3; ? else block
statement 4;
}
Flow Diagram
Object Oriented Programming and C++
Example 1:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
else
{
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100
Example 2:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is not matching
Exact value of a is : 100
Example :
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
// check the boolean condition
if( a == 100 )
{
// if condition is true then check the following
if( b == 200 )
{
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
Object Oriented Programming and C++
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
In C++ Goto statement is used to transfer the control to anywhere in the program. This is an
unconditional statement and should be used when you do not have any other choice.
Syntax of a Goto Statement:-
Goto A;
A:
{
Object Oriented Programming and C++
Statements
};
Example of a Goto statement:-
#include<iostream.h>
#include<conio.h>
main()
{
for(int y=0; y<3; y++)
{
cout<<" The User is a very good programmer :"<<endl;
if(y==3)
{
cout<<" It was a Mistake :"<<endl;
goto a;
}
}
cout<<endl;
a:
{
cout<<" It is a result of goto statement ";
}s
getch();
}
THE break STATEMENT
The break statement allows the programmer to terminate the loop .The break skips from the
loop or the block in which it is defined
The control then automatically passes on to the first statement after the loop or the block.
The break statement can be associated with all the conditional statements
(especially switch( ) case.
In loops, the break statement ends execution of the nearest enclosing do, for, or while
statement. Control passes to the statement that follows the ended statement, if any.
Within nested statements, the break statement ends only the do, for, switch, or while statement
that immediately encloses it. You can use a return or goto statement to transfer control from
more deeply nested structures.
We can also use break statements in the nested loops .If we use break statement in the
innermost loop, then the control of program is terminated from that loop only and resumes at the
next statement following that loop.
The widest use of this statement is in switch case where it is used to avoid flow of control
from one case to other.
Example of a Break Statement:-
#include<iostream.h>
#include<conio.h>
main()
{
for(int y=0; y<5; y++)
{
cout<<" The User is a very good programmer :"<<endl;
break;
}
cout<<" The User is a very bad programmer :"<<endl;
getch();
}
Object Oriented Programming and C++
As you can see “The user is a good programmer” have been printed only one time and after that
the statement “The user is not a good programmer” is printed because during first iteration due to
break statement loop runs only one time.
The continue statement works quite similar to the break statement. Instead of forcing the
control to end of loop (as it is in case of break), continue causes the control to pass on to the
beginning of the block/loop.
In case of for loop, the continue case causes the condition testing and incrementation
steps to be executed (while rest of the statements following continue are neglected).
For while and do-while, continue causes control to pass on to conditional tests.
It is useful in programming situation when you want particular iterations to occur only up
to some extent or you want to neglect some part of your code. The programs
on break and continue can be performed by the programmer.
a break statement is found or end of switch block is reached. If not then simply default (if
present) is executed (if default isn't present then simply control flows out of the switch block).
The default is normally present at the bottom of switch case structure. But we can also define
default statement anywhere in the switch structure.
The default block must not be empty. Every case statement terminates with: (colon).
The break statement is used to stop the execution of succeeding cases and pass the control to the
switch end of block. The syntax of the switch ( ) case statement is shown below. The following
program simulates the working of switch ( ) case statement.
Syntax:
switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}
The expression used in a switch statement must have an integral or enumerated type, or be
of a class type in which the class has a single conversion function to an integral or
enumerated type.
You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
Object Oriented Programming and C++
Flow Diagram:
Example:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
Object Oriented Programming and C++
return 0;
}
You passed
Your grade is D
OUTPUT
Enter a number :5
LOOPS IN C/C++
C/C++ provides loop structures for performing some tasks which are repetitive in nature. The
C/C++ language supports three types of loop control structures. Their syntax is described.
The for loop comprises of three actions. The three actions are placed in the for statement
itself. The three actions initialize counter, test condition, and re-evaluation parameters are
included in one statement. The expressions are separated by semi-colons (;). This helps the
programmer to visualize the parameters easily.
Object Oriented Programming and C++
The for statement is equivalent to the while and do-while statements. The only difference
between for and while is that the latter checks the logical condition and then executes the body of
the loop, whereas the for statement test is always performed at the beginning of the loop. The
body of the loop may not be executed at all times if the condition fails at the beginning. The do-
while loop executes the body of the loop at least once regardless of the logical condition
After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.
Object Oriented Programming and C++
Flow Diagram:
Example:
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for ( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Object Oriented Programming and C++
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the
for(;;) construct to signify an infinite loop.
}
The test condition may be any expression. The loop statements will be executed till the
condition is true i.e., the test condition is evaluated and if the condition is true, then the body of
the loop is executed. When the condition becomes false the execution will be out of the loop.
The block of the loop may contain single statement or a number of statements. The same
block can be repeated. The braces are needed only if the body of the loop contains more than one
statement. However, it is a good practice to use braces even if the body of the loop contains only
one statement.
Flow Diagram:
Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
Object Oriented Programming and C++
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example Program:
#include<iostream>
#include<conio.h>
int main()
{
// Variable Declaration
int a;
int counter = 1;
//while Loop Block
while (counter <= a)
{
cout<<"Execute While "<<counter<<" time"<<endl;
counter++;
}
# include <iostream.h>
# include <constream.h>
# include <math.h>
void main( )
{
int y,x=1;
clrscr( );
cout <<"\n\tNumbers and their cubes \n";
do
{
y=pow(x,3);
cout <<"\t"<<x<<"\t\t"<<y<<"\n";
x++;
} while (x<=10);
}
Example Program:
#include<iostream>
#include<conio.h>
int main()
{
// Variable Declaration
int a;
// Get Input Value
cout<<"Enter the Number :";
cin>>a;
int counter = 1;
//Do while Loop Block
do
{
cout<<"Execute Do While "<<counter<<" time"<<endl;
counter++;
}while (counter <= a);
INTRODUCTION
When the concept of function or sub-program was not introduced, the programs were large in
size and code got repeated. It was very difficult to debug and update these large programs
because many bugs were encountered. When the functions and sub-programs are introduced, the
programs are divided into a number of segments and code duplication is avoided. Bugs in small
Object Oriented Programming and C++
programs can be searched easily and this step leads to the development of complex programs
with functions.
One of the features of C/C++ language is that a large sized program can be divided into
smaller ones. The smaller programs can be written in the form of functions. The process of
dividing a large program into tiny and handy sub-programs and manipulating them
independently is known as modular programming. This technique is similar to divide-and-
conquer technique. Dividing a large program into smaller functions provides advantages to the
programmer. The testing and debugging of a program with functions becomes easier. A function
can be called repeatedly based on the application and thus the size of the program can be
reduced. The message passing between a caller (calling function) and callee (called function)
takes places using arguments. The concept of modular approach of C++ is obtained from
function. Following are the advantages of functions:
int main( );
int main(int argc, char *argv[]);
The return statement is used to return value. If there is no return statement, compiler displays
a warning message “Function should return a value”.
PARTS OF FUNCTION
A function has the following parts:
(a) Function prototype declaration
(b) Definition of a function (function declarator)
(c) Function call
(d) Actual and formal arguments
(e) The return statement?
Function Prototypes
We use many built-in functions. The prototypes of these functions are given in the
respective header files. We include them using # include directive. In C++, while defining user-
defined functions, it is unavoidable to declare its prototype. A prototype statement helps the
compiler to check the return and argument types of the function.
A function prototype declaration consists of the function return type, name, and arguments
list. It tells the compiler (a) the name of the function, (b) the type of value returned, and (c) the
type and number of arguments.
PASSING ARGUMENTS
The main objective of passing argument to function is message passing. The message
passing is also known as communication between two functions i.e., between caller and callee
functions. There are three methods by which we can pass values to the function. These methods
are.
(a) Call by value (pass by value),
(b) Call by address (pass by address), and
(c) Call by reference (pass by reference).
Object Oriented Programming and C++
C++ supports all these three types of passing values to the function whereas C supports only
the first two types. The arguments used to send values to function are known as input-arguments.
The arguments used to return results are known as output arguments. The arguments used to send
as well as return results are known as input-output arguments. While passing values the
following conditions should be fulfilled.
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function.
A called function performs defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value. For example:
return result;
}
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
The result is 8
This program is divided in two functions: addition and main. Remember that no matter the
order in which they are defined, a C++ program always starts by calling main. In fact, main is the
only function called automatically, and the code in any other function is only executed if its
function is called from main (directly or indirectly).
In the example above, main begins by declaring the variable z of type int, and right after that,
it performs the first function call: it calls addition. The call to a function follows a structure very
similar to its declaration. In the example above, the call to addition can be compared to its
definition just a few lines earlier:
The parameters in the function declaration have a clear correspondence to the arguments
passed in the function call. The call passes two values, 5 and 3, to the function; these correspond
to the parameters a and b, declared for function addition.
At the point at which the function is called from within main, the control is passed to function
addition: here, execution of main is stopped, and will only resume once the addition function
ends. At the moment of the function call, the value of both arguments (5 and 3) are copied to the
local variables int a and int b within the function.
Then, inside addition, another local variable is declared (int r), and by means of the
expression r=a+b, the result of a plus b is assigned to r; which, for this case, where a is 5 and b is
3, means that 8 is assigned to r.
The final statement within the function:
return r;
Ends function addition, and returns the control back to the point where the function was
called; in this case: to function main. At this precise moment, the program resumes its course on
main returning exactly at the same point at which it was interrupted by the call to addition. But
additionally, because addition has a return type, the call is evaluated as having a value, and this
value is the value specified in the return statement that ended addition: in this particular case, the
value of the local variable r, which at the moment of the return statement had a value of 8.
Therefore, the call to addition is an expression with the value returned by the function, and in
this case, that value, 8, is assigned to z. It is as if the entire function call (addition(5,3)) was
replaced by the value it returns (i.e., 8).
Then main simply prints this value by calling:
cout << "The result is " << z;
assignment statement. For example, suppose x and y are non-constant integer identifiers with
appropriate allocated memory. Their lvalues are changeable. The following expressions are
legal:
int arr[] = {1, 2};
int* p = &arr[0];
*(p + 1) = 10; // OK: p + 1 is an rvalue, but *(p + 1) is an lvalue
RETURN BY REFERENCE
We have studied the reference variable and it's functioning. A reference allows creating
alias for the preexisting variable. A reference can also be returned by the function. A function
that returns reference variable is in fact an alias for referred variable. This technique of returning
reference is used to establish cascade of member functions calls in operator overloading.
Consider the following example
The program given below illustrates return by reference.
Write a program to return a value by reference.
# include <iostream.h>
# include <constream.h>
void main( )
{
clrscr( );
int & min ( int &j, int &k);
int a=18,b=11,c;
c=min (a,b);
cout <<"Minimum Value = "<<c;
}
int & min(int &j, int &k)
{
if (k<j ) return k;
else
return j;
}
Write a program to return more than one value from function by reference.
# include <iostream.h>
# include <constream.h>
void main( )
{
int sq,cb,n;
void more(int &, int &, int);
cout <<"\n Enter a Number : ";
cin>>n;
more(sq,cb,n);
cout <<"\n Square ="<<sq;
Object Oriented Programming and C++
DEFAULT ARGUMENTS
Usually, a function is called with all the arguments as declared in function prototype
declaration and function definition. C++ compiler lets the programmer to assign default values in
the function prototype declaration/function declarator of the function. When the function is
called with less parameter or without parameters, the default values are used for the operations.
It is not allowed to assign default value to any variable, which is in between the variable list.
Variables lacking default values are written first, followed by the variables containing default
values. This is because the convention of storing variables on the stack in C++ is from right to
left.
The default values can be specified in function prototype declaration or function declarator.
Normally, the default values are placed in function prototype declaration. In case the function is
defined before caller function, then there is no need to declare function prototype. Hence, the
default arguments are placed in function declarator. The compiler checks for the default values in
function prototype and function declarator and provides these values to those arguments that are
omitted in function call.
# include <constream.h>
void main( )
{
clrscr( );
int input(void);
void display ( int = input( ) );
display(20); // first call with argument
display( ); // second call with default argument
}
void display( int j)
{
cout <<"\nInteger is : "<<j;
}
input( )
{
int k;
cout <<"\n Enter an integer : ";
cin >>k;
return k;
}
INLINE FUNCTIONS
One of the prime factors behind using function is that code duplication in program is
avoided and memory space is saved. When a function is defined and invoked, one set of
instruction is created in the memory of the system. At each call, the control passes to the
subroutine at a specified address in the memory. The CPU stores the memory address of
instruction following the function calls into the stack and also pushes the arguments in the stack
area. The compiler runs the function, stores the return values in a memory location or register
and when execution completes, the control returns to the calling function. After this, execution
resumes immediately to the next line following the function call statement. If the same function
is called....
FUNCTION OVERLOADING
It is possible in C++ to use the same function name for a number of times for different
intentions. Defining multiple functions with same name is known as function overloading or
function polymorphism. Polymorphism means one function having many forms. The overloaded
function must be different in its argument list and with different data types. The examples of
overloaded functions are given below. All the functions defined should be equivalent to their
prototypes.
int sqr (int);
float sqr (float);
long sqr (long);
C++ program for function overloading. Function overloading means two or more
functions can have the same name but either the number of arguments or the data type of
arguments has to be different. Return type has no role because function will return a value when
it is called and at compile time compiler will not be able to determine which function to call. In
the first example in our code we make two functions one for adding two integers and other for
adding two floats but they have same name and in the second program we make two functions
with identical names but pass them different number of arguments. Function overloading is also
known as compile time polymorphism.
(1) If two functions have the similar type and number of arguments (data type), the function
cannot be overloaded. The return type may be similar or void, but argument data type or
number of arguments must be different. For example,
(a) sum(int,int,int);
sum(int,int);
Here, the above function can be overloaded. Though data type of arguments in both the
functions are similar but number of arguments are different.
(b) sum(int,int,int);
sum(float,float,float);
In the above example, numbers of arguments in both the functions are same, but data types
are different. Hence, the above function can be overloaded.
(2) Passing constant values directly instead of variables also result in ambiguity. For
example,intsum(int,int);
floatsum(floatfloatfloat);
Here, sum( ) is an overloaded function for integer and float values. If values are passed
as follows
sum(2,3);
sum(1.1,2.3,4.3);
the compiler will flag an error because the compiler cannot distinguish between these two
functions. Here, internal conversion of float to int is possible. Hence, in both the above calls
integer version of function sum ( ) is executed.
LIBRARY FUNCTIONS
ceil, ceill and floor, floorl
The functions ceil and ceill round up the given float number. Whereas the functions floor
and floorl round down the float number. They are defined in math.h header file. Their
declarations are given below:
Declaration
double ceil (double n);
double floor (double n);
long double ceill (long double(n));
long double floorl (long double (n));
The given below program illustrates the working of these functions.
Write a program to round down and up the given float number.
#include <math.h>
#include <iostream.h>
# include <conio.h>
void main(void)
Object Oriented Programming and C++
{
clrscr( );
float num = 3.12;
float d, u;
d = floor(num);
u = ceil(num);
cout <<"\n Original number is : "<<num;
cout <<"\n Number rounded up is : "<<u;
cout <<"\n Number rounded down is : " <<d;
}
QUESTIONS
UNIT-I
SECTION-A
1. C++ was developed by_________
2. Expand POP & OOP.
3. List any five basic concepts of OOP
4. ___________ are the basic runtime entities in object oriented system.
5. Define Encapsulation?
6. Define operator and function overloading?
7. Give few examples for pure object oriented languages?
8. Define Idenifiers?
9. Define scope resolution operator?
10. What's the difference between signed and unsigned datatype.
SECTION-B
1. Write the principles of object oriented programming?
2. Describe about software crsis?
3. Write about procedure oriented programming?
4. Write short notes on application of OOP?
5. Write short notes on operators in c++?
6. Describe about tokens used in C++ program?
7. Write a sample program using manipulators in C++?
8. Write a Sample program using control structures in c++?
9. Describe about various types of expressions?
10. Differentiate OOP and POP?
SECTION-C
1. Explain the concepts of control structures in c++ using a sample program?
2. Explain any five operators in c++ using a Sample program?
3. Explain about various operators used in C++?
4. List out the various benefits of OOPS.
5. Write in detail about Inheritance and Polymorphism with neat diagram?
6. Explain about Object oriented programming with a neat diagram?
7. Explain briefly about Software evolution with differnet layers of Computer
8. software?
9. Explain the principles of object oriented programming?
10. Explain about procedure oriented programming with diagram for its structure?
11. Explain about dynamic binding and message passing?
INTRODUCTION
In C, structures are used to combine one or more data types. Functions are not permitted as
members in structures. Later objects are declared which hold individual copies of member
variables of structure. Objects can access the data members of the structures directly. Any
outside function is also able to access the data members of the structure through the object. Thus,
there is no security to member variables declared inside the structure in C as shown below.
Fig.Structure in C
In C++, structure also combines functions with data members. C++ introduces a new
keyword class. A class in C++ is similar to structure. Using class or structure, a programmer can
merge one or more dissimilar data types and a new custom data type can be created. A class is
nothing but grouping of variables of different data types with functions. Each variable of a class
is called as member variable. Functions are called as member functions or methods.
STRUCTURES IN C
Though, it is possible to combine more than one variable using structure in C, the structure
has following limitations when used in C:
Only variables of different data types can be declared in the structure as member functions are
not allowed as members.
Direct access to data members is possible. It is because by default all the member variables are
public. Hence, security to data or data hiding is not provided.
The struct data type is not treated as built in type i.e., use of struct keyword is necessary
to declare objects.
The member variables cannot be initialized inside the structure.
The syntax of structure declaration is as follows:
Syntax:
struct<struct name>
{
Variable1;
Variable2;
};
STRUCTURES IN C++
No doubt, C++ has made various improvements in structure. To know the improvements
made in C++, the last program is compiled and executed with C++ compiler. The explanation
followed by this program discusses the various improvements.
Write a program to declare struct. Initialize and display contents of member variables.
# include <iostream.h>
Object Oriented Programming and C++
# include <constream.h>
struct item // struct declaration
{
int codeno; // codeno=200 not possible
float prize;
int qty;
};
void main( )
{
item a,*b; // object declaration
clrscr( );
a.codeno=123; // direct access & initialization of member variables
a.prize=150.75;
a.qty= 150;
cout <<"\n With simple variable";
cout <<"\n Codeno : "<<a.codeno;
cout <<"\n Prize : "<<a.prize;
cout <<"\n Qty : "<<a.qty;
b->codeno=124; // direct access & initialization of member variables
b->prize=200.75;
b->qty= 75;
cout <<"\n\n With pointer to structure";
cout <<"\n Codeno : "<<b->codeno;
cout <<"\n Prize : "<<b->prize;
cout <<"\n Qty : "<<b->qty;
}
CLASSES IN C++
Classes and structure are the same with only a small difference that is explained later. The
following discussion of class is applicable to struct too.
The whole declaration of class is given. The class is used to pack data and function together.
The class has a mechanism to prevent direct access to its members, which is the central idea of
object-oriented programming. The class declaration is also known as formation of new abstract
data type.
The abstract data type can be used as basic data type such as int, float etc. The class consists
of member data variables that hold data and member functions that operate on the member data
variables of the same class.
Syntax and an example of class
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
class Rectangle
{
int width, height;
public:
void set_values (int,int);
int area (void);
Object Oriented Programming and C++
} rect;
DECLARING OBJECTS
A class declaration only builds the structure of object. The member variables and functions are
combined in the class. The declaration of objects is same as declaration of variables of basic data
types. Defining objects of class data type is known as class instantiation. When objects are
created only during that moment, memory is allocated to them.
Consider the following examples:
int x,y,z; // Declaration of integer variables
char a,b,c; // Declaration of character variables
item a,b, *c; // Declaration of object or class type variables
In example (a) three variables x, y and z of integer types are declared. In example (b) three
variables a, b and c of char type are declared. In the same fashion the third example declares the
three objects a, b and c of class item. The object *c is pointer to class item.
Because Date’s members are now public, they can be accessed by main ().
A public member is accessible from anywhere outside the class but within a program. You can
set and get the value of public variables without any member function as shown in the following
example:
Object Oriented Programming and C++
#include <iostream>
using namespace std;
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
clrscr( );
item one; // object declaration
one.codeno=123; // member initialization
one.price=123.45;
one.qty=150;
}
A private member variable or function cannot be accessed, or even viewed from outside
the class. Only the class and friend functions can access private members.
By default all the members of a class would be private, for example in the following class
width is a private member, which means until you label a member, it will be assumed a private
member:
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
Example:
#include <iostream>
using namespace std;
class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result:
Length of box : 10
Width of box : 10
A protected member variable or function is very similar to a private member but it provided
one additional benefit that they can be accessed in child classes which are called derived classes.
This program shows width member will be accessible by any member function of its
derived class SmallBox.
#include <iostream>
using namespace std;
class Box
{
protected:
double width;
};
class SmallBox:Box // SmallBox is the derived class.
{
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void)
{
Object Oriented Programming and C++
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}
// Main function for the program
int main( )
{
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Width of box : 5
The difference between member and normal function is that the former function can be
invoked freely where as the latter function only by using an object of the same class.
The same function can be used in any number of classes. This is possible because the
scope of the function is limited to their classes and cannot overlap one another.
The private data or private function can be accessed by public member function. Other
functions have no access permission.
The member function can invoke one another without using any object or dot operator.
To write a program to find the multiplication values and the cubic values using inline
function.
#include<iostream.h>
#include<conio.h>
class line
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
Object Oriented Programming and C++
{
return(x*x*x);
}
};
void main()
{
line obj;
float val1,val2;
clrscr();
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:"<<obj.mul(val1,val2);
cout<<"\n\nCube value is :"<<obj.cube(val1)<<"\t"<<obj.cube(val2);
getch();
}
Output:
Enter two values: 5 7
Multiplication Value is: 35
Cube Value is: 25 and 343
}
void Display()
{
cout<<"Square Is:"<<Num*Num;
}
};
void main()
{
Square Obj;
Obj.Get();
Obj.Display();
getch()
}
CLASSES, OBJECTS AND MEMORY
Objects are the identifiers declared for class data type. Object is a composition of one or more
variables declared inside the class. Each object has its own copy of public and private data
members. An object can have access to its own copy of data members and have no access to data
members of other objects.
Only declaration of a class does not allocate memory to the class data members. When an
object is declared memory is reserved for data members only and not for member
functions.Consider the following program.
Write a program to declare objects and display their contents.
# include <iostream.h>
# include <constream.h>
class month
{
public:
char *name;
int days;
}; // end of class
int main ( )
{
clrscr( );
month M1,M3; // object declaration
M1.name="January";
M1.days=31;
M3.name="March";
M3.days=31;
cout <<"\n Object M1 ";
cout <<"\n Month name : "<<M1.name <<" Address
:"<<(unsigned)&M1.name;
cout <<"\n Days :" <<M1.days <<"\t\t Address : "<<(unsigned)&M1.days;
cout <<"\n\n Object M3 ";
cout <<"\n Month name : "<<M3.name <<"\t Address :
"<<(unsigned)&M3.name;
cout <<"\n Days :" <<M3.days <<"\t\t Address : "<<(unsigned)&M3.days;
return 0;
}
STATIC MEMBER VARIABLES AND FUNCTIONS
Static Member Variables
Object Oriented Programming and C++
We have noticed earlier that each object has its separate set of data member variables in
memory. The member functions are created only once and all objects share the functions. No
separate copy of function of each object is created in the memory like data member variables.
It is possible to create common member variables like function using the static keyword.
Once a data member variable is declared as static, only one copy of that member is created for
the whole class. The static is a keyword used to preserve value of a variable. When a variable is
declared as static it is initialized to zero. A static function or data element is only recognized
inside the scope of the present class.
STATIC OBJECT
In C, it is common to declare variable static that gets initialized to zero. The object is a
composition of one or more member variables. There is a mechanism called constructor to
initialize member variables of the object to desired values. The constructors are explained in next
chapter. The keyword static can be used to initialize all class data member variables to zero.
Declaring object itself as static can do this. Thus, all its associated members get initialized to
zero. The following program illustrates the working of static object.
ARRAY OF OBJECTS
Arrays are collection of similar data types. Arrays can be of any data type including user-
defined data type, created by using struct, class and typedef declarations. We can also create an
array of objects. The array elements are stored in continuous memory locations. Consider the
following example:
class player
{
Object Oriented Programming and C++
private:
char name [20];
int age;
public:
void input (void);
void display (void);
};
In the example given above player is a user-defined data type and can be used to declare an
array of object of type player. Each object of an array has its own set of data variables.
player cricket[5];
player football[5];
player hockey[5];
As shown above, arrays of objects of type player are created. The array cricket[5] contains
name, age and information for five objects. The next two declarations can maintain the same
information for other players in arrays hockey [5] and football [5]. These arrays can be initialized
or accessed like an ordinary array. The program given below describes the working of array of
objects.
Example Program for Array of Objects:
#include <iostream.h>
const int MAX =100;
class Details
{
private:
int salary;
float roll;
public:
void getname( )
{
cout << "\n Enter the Salary:";
cin >> salary;
cout << "\n Enter the roll:";
cin >> roll;
}
void putname( )
{
cout << "Employees" << salary <<
"and roll is" << roll << '\n';
}
};
void main()
{
Details det[MAX];
int n=0;
char ans;
do{
cout << "Enter the Employee Number::" << n+1;
det[n++].getname;
cout << "Enter another (y/n)?: " ;
cin >> ans;
} while ( ans != 'n' );
for (int j=0; j<n; j++)
{
Object Oriented Programming and C++
Result:
Enter the Employee Number:: 1
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: y
Enter the Employee Number:: 2
Enter the Salary:20
Enter the roll:30
Enter another (y/n)?: n
In the above example an array of object "det" is defined using the user defined data type
"Details". The class element "getname()" is used to get the input that is stored in this array of
objects and putname() is used to display the information.
friend FUNCTIONS
The central idea of encapsulation and data hiding concept is that any non-member function
has no access permission to the private data of the class. The private members of the class are
accessed only from member functions of that class. Any non-member function cannot access the
private data of the class.
C++ allows a mechanism, in which a non-member function has access permission to the
private members of the class. This can be done by declaring a non-member function friend to the
class whose private data is to be accessed. Here friend is a keyword.
Consider the following example:
class ac
{
private:
char name [15];
int acno;
float bal;
public:
void read( );
friend void showbal( );
};
Object Oriented Programming and C++
The keyword friend must precede the function declaration whereas function declarator must
not. The function can be defined at any place in the program like normal function. The function
can be declared as friend function in one or more classes. The keyword friend or scope access
operator must not precede the definition of friend function. The declaration of friend function is
done inside the class in private or public part and a function can be declared as friend function in
any number of classes.
A friend function of a class is defined outside that class' scope but it has the right to access
all private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.
A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
To declare a function as a friend of a class, precede the function prototype in the class
definition with keyword friend as follows:
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare all member functions of class ClassTwo as friends of class ClassOne, place a
following declaration in the definition of class ClassOne:
friend class ClassTwo;
#include <iostream>
using namespace std;
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid )
{
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box )
{
/* Because setWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
int main( )
{
Box box;
// set box width without member function
box.setWidth(10.0);
Object Oriented Programming and C++
else
f=f+m+tri_num(m-1);
return (f);
}
};
void main( )
{
clrscr( );
num a;
int x;
cout <<"\n Enter a number : ";
cin>>x;
cout<<"Triangular number of "<<x<<" is : "<<a.tri_num(x);
}
LOCAL CLASSES
When a class is declared inside a function they are called as local classes. The local
classes have access permission to global variables as well as static variables. The global
variables need to be accessed using scope access operator when the class itself contains member
variable with same name as global variable. The local classes should not have static data member
and static member functions. If at all they are declared, the compiler provides an error message.
The progdddrams given next illustrate the local classes.
Write a program to define classes inside and outside main( ) function and access the
elements.
# include <iostream.h>
# include <conio.h>
class A
{
private :
int a;
public :
void get( )
{
cout <<"\n Enter value for a : ";
cin >>a;
}
void show( )
{ cout <<endl<<" a = " <<a; }
};
main( )
{
clrscr( );
class B
{
int b;
public :
void get( )
{
cout <<"\n Enter value for b : ";
cin >>b;
Object Oriented Programming and C++
}
void show( )
{
cout <<" b = " <<b;
}
};
A j;
B k;
j.get( );
k.get( );
j.show( );
k.show( );
return 0;
}
Empty Classes
class nodata { };
class vacant { };
We can also precede the declaration of classes by the keywords static, const, volatile etc. But
there is no effect in the class operations. Such declaration can be done as follows:
Classes and other keywords
static class boys { };
const class data { };
volatile class area { };
public:
void main( )
{
cout <<endl<<"In member function main( )";
}
};
void main( )
{
clrscr( );
A *a;
a->main( );
}
OUTPUT
In member function main ( )
Explanation: In the above program, class A is declared and has one member function main ( ).
In the non-member function main ( ), the object a invokes the member function main ( ) and a
message is displayed as shown in the output.
{
double ans;
ans=fabs(d);
return(ans);
}
int main( )
{
clrscr( );
absv n;
cout <<"\n Absolute value of -25 is "<<n.num(-25);
cout <<"\n Absolute value of -25.1474 is "<<n.num(-25.1474);
return 0;
}
Write a program to call function main ( ) using indirect recursion. // Indirect Recursion
Using OOP //
# include <iostream.h>
# include <conio.h>
int main (int);
class rec
{
int j;
public:
int f;
rec (int k, int i)
{
clrscr( );
cout<<"[ ";
f=i;
j=k;
}
~rec ( )
{ cout <<"\b\b] Factorial of number : "<<f ; }
void pass( )
{
cout<<main (j--)<<" * ";
}
};
rec a(5,1);
main(int x)
{
if (x==0)
return 0;
a.pass( );
a.f=a.f*x;
return x;
}
INTRODUCTION
When a variable is declared and if not initialized, it contains garbage value. The compiler
itself cannot carry out the process of initialization of a variable. The programmer needs explicitly
to assign a value to the variable. Initialization prevents the variable from containing garbage
value.
Consider an example
float height; // variable declaration
Object Oriented Programming and C++
class num
{
private:
int a;
float b;
char c;
public:
(a) num (int m, float j , char k);
(b) num (int m, float j);
(c) num ( );
(d) class num x (4,5.5,‘A’);
(e) class num y (1,2.2);
(f) class num z;
Definition
In C++, Constructor is automatically called when object (instance of class) create. It is special
member function of the class. Which constructor has arguments that are called Parameterized
Constructor.
One Constructor overload another constructor is called Constructer Overloading
It has same name of class.
It must be a public member.
No Return Values.
Default constructors are called when constructors are not defined for the classes.
Syntax
class class-name
{
Access Specifier:
Member-Variables
Member-Functions
public:
class-name()
{
// Constructor code
}
class-name(variables)
{
// Constructor code
}
... other Variables & Functions
}
Example Program
/* Example Program For Simple Example Program Of Constructor Overloading In C++
*/
#include<iostream>
#include<conio.h>
using namespace std;
class Example
{
// Variable Declaration
int a,b;
Object Oriented Programming and C++
public:
//Constructor wuithout Argument
Example()
{
// Assign Values In Constructor
a=50;
b=100;
cout<<"\nIm Constructor";
}
//Constructor with Argument
Example(int x,int y) {
// Assign Values In Constructor
a=x;
b=y;
cout<<"\nIm Constructor";
}
void Display() {
cout<<"\nValues :"<<a<<"\t"<<b;
}
};
int main() {
Example Object(10,20);
Example Object2;
// Constructor invoked.
Object.Display();
Object2.Display();
// Wait For Output Screen
getch();
return 0;
}
Sample Output
Im Constructor
Im Constructor
Values: 10 20
Values: 50 100
{
private:
int num;
int power;
int ans;
public :
power (int n=9,int p=3); //
declaration of constructor with default argu-ments
void show( )
{
cout <<"\n"<<num <<" raise to "<<power <<" is " <<ans;
}
};
power :: power (int n,int p )
{
num=n;
power=p;
ans=pow(n,p);
}
main( )
{
clrscr( );
class power p1,p2(5);
p1.show( );
p2.show( );
return 0;
}
COPY CONSTRUCTORS
The constructor can accept arguments of any data type including user-defined data types and an
object of its own class.
Table : Copy constructors
Statement (a) Statement (b)
class num class num
{ {
private: private:
---- ----
---- ----
---- ----
public: public:
num(num); num(num…);
} }
In statement (a) an argument of the constructor is same as that of its class. Hence, this
declaration is wrong. It is possible to pass reference of object to the constructor. Such declaration
is known as copy constructor. The statement (b) is valid and can be used to copy constructor.
When we pass an object by value into a function, a temporary copy of that object is created.
All copy constructors require one argument, with reference to an object of that class. Using copy
constructors, it is possible for the programmers to declare and initialize one object using
reference of another object. Thus, whenever a constructor is called a copy of an object is created.
#include<conio.h>
using namespace std;
class Example
{
// Variable Declaration
int a,b;
public:
//Constructor with Argument
Example(int x,int y)
{
// Assign Values In Constructor
a=x;
b=y;
cout<<"\nIm Constructor";
}
void Display()
{
cout<<"\nValues :"<<a<<"\t"<<b;
}
};
int main()
{
Example Object(10,20);
//Copy Constructor
Example Object2=Object;
// Constructor invoked.
Object.Display();
Object2.Display();
// Wait For Output Screen
getch();
return 0;
}
DESTRUCTORS
Destructor is also a special member function like constructor. Destructors destroy the class
objects created by constructors. The destructors have the same name as their class, preceded by a
tilde (~).
For local and non-static objects, the destructor is executed when the object goes out of scope.
In case the program is terminated by using return or exit ( ) statements, the destructor is executed
for every object existing at that time. It is not possible to define more than one destructor. The
destructor is only one way to destroy the object. Hence, they cannot be overloaded.
Object Oriented Programming and C++
A destructor neither requires any argument nor returns any value. It is automatically called
when object goes out of scope. Destructor releases memory space occupied by the objects.
Destructors are usually used to deallocate memory and do other cleanup for a class object and
its class members when the object is destroyed. A destructor is called for a class object when that
object passes out of scope or is explicitly deleted.
A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For
example:
class X {
public:
// Constructor for class X
X();
// Destructor for class X
~X();
};
A destructor takes no arguments and has no return type. Its address cannot be taken.
Destructors cannot be declared const, volatile, const volatile or static. A destructor can
be declared virtual or pure virtual.
If no user-defined destructor exists for a class and one is needed, the compiler implicitly
declares a destructor. This implicitly declared destructor is an inline public member of its class.
The compiler will implicitly define an implicitly declared destructor when the compiler uses
the destructor to destroy an object of the destructor's class type. Suppose a class A has an
implicitly declared destructor. The following is equivalent to the function the compiler would
implicitly define for A:
A::~A() { }
The compiler first implicitly defines the implicitly declared destructors of the base classes and
nonstatic data members of a class A before defining the implicitly declared destructor of A
A destructor of a class A is trivial if all the following are true:
It is implicitly defined
All the direct base classes of A have trivial destructors
The classes of all the nonstatic data members of A have trivial destructors
If any of the above is false, then the destructor is nontrivial. A union member cannot be of a
class type that has a nontrivial destructor.
Class members that are class types can have their own destructors. Both base and derived
classes can have destructors, although destructors are not inherited. If a base class A or a member
of A has a destructor, and a class derived from A does not declare a destructor, a default
destructor is generated.
The default destructor calls the destructors of the base class and members of the derived class.
The destructors of base classes and members are called in the reverse order of the completion
of their constructor:
The destructor for a class object is called before destructors for members and bases are
called.
Destructors for nonstatic members are called before destructors for base classes are
called.
Destructors for nonvirtual base classes are called before destructors for virtual base
classes are called.
When an exception is thrown for a class object with a destructor, the destructor for the
temporary object thrown is not called until control passes out of the catch block.
Destructors are implicitly called when an automatic object (a local object that has been
declared auto or register, or not declared as static or extern) or temporary object passes out
of scope. They are implicitly called at program termination for constructed external and static
Object Oriented Programming and C++
objects. Destructors are invoked when you use the delete operator for objects created with the
new operator.
For example:
#include <string>
class Y
{
private:
char * string;
int number;
public:
// Constructor
Y(const char*, int);
// Destructor
~Y() { delete[] string;
}
};
// Define class Y constructor
Y::Y(const char* n, int a) {
string = strcpy(new char[strlen(n) + 1 ], n);
number = a;
}
int main ()
{
// Create and initialize
// object of class Y
Y yobj = Y("somestring", 10);
// ...
// Destructor ~Y is called before
// control returns from main()
}
A destructor can be used explicitly to destroy objects, although this practice is not
recommended. However to destroy an object created with the placement new operator, you can
explicitly call the object's destructor. The following example demonstrates this:
#include <new>
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A::A()" << endl; }
~A() { cout << "A::~A()" << endl; }
};
int main ()
{
char* p = new char[sizeof(A)];
A* ap = new (p) A;
ap->A::~A();
delete [] p;
}
The statement A* ap = new (p) A dynamically creates a new object of type A not in the free
store but in the memory allocated by p. The statement delete [] p will delete the storage
allocated by p, but the run time will still believe that the object pointed to by ap still exists until
you explicitly call the destructor of A (with the statement ap->A::~A()).
Object Oriented Programming and C++
ANONYMOUS OBJECTS
Objects are created with names. It is possible to create objects without name and such
objects are known as anonymous objects. When constructors and destructors are invoked, the
data members of the class are initialized and destroyed respectively. Thus, without object we can
initialize and destroy the contents of the class. All these operations are carried out without object
or we can also assume that the operations are carried out using an anonymous object, which
exists but is hidden. The second thought is correct because if we apply pointer this(explained in
Chapter “Pointers and Arrays”) we get the address of the object. It is not possible to invoke
member function without using objects but we can invoke special member
functions constructors and destructors which compulsorily exist in every class. Thus, without
use of constructor and destructor the theory of anonymous object cannot be implemented in
practical. Consider the following example.
private:
int x;
~A( ) { cout <<"\n In destructor ~A( )"; }
A( ) {x=7; cout <<"\n In constructor A( )"; }
public:
void show( )
{
this->A::A( ); // invokes constructor
cout <<endl<<" x = "<<x;
this->A::~A( ); // invoke destructor
}
};
void main( )
{
clrscr( );
A *a;
a->show( );
}
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void)
{
cout << "Object is being created" << 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);
Object Oriented Programming and C++
When the above code is compiled and executed, it produces the following result:
Write a program to use new and delete operators with constructor and destructor.
Allocate memory for given number of integers. Also release the memory.
# include <iostream.h>
# include <conio.h>
int number (void);
class num
{
int *x;
int s;
public :
num( )
{
s=number( );
x= new int [s];
}
~num( ) { delete x; }
void input( );
void sum( );
};
void num :: input( )
{
for ( int h=0;h<s;h++)
{
cout <<"Enter number ["<<h+1<< "] : ";
cin>>x[h];
}
}
void num :: sum( )
{
int adi=0;
for ( int h=0;h<s;h++)
adi+=x[h];
Object Oriented Programming and C++
void main( )
{
num n1;
n1.input( );
n1.sum( );
}
void main( )
{
clrscr( );
class main a;
}
RECURSIVE CONSTRUCTOR
Like normal and member functions, constructors also support recursion. The program given next
explains this.
Write a program to invoke constructor recursively and calculate the triangular number of
the entered number.
# include <iostream.h>
# include <conio.h>
# include <process.h>
class tri_num
Object Oriented Programming and C++
{
int f;
public :
tri_num( ) { f=0; }
void sum( int j) { f=f+j; }
tri_num(int m)
{
if (m==0)
{
cout <<"Triangular number : "<<f;
exit(1);
}
sum(m);
tri_num::tri_num(--m);
}
};
void main( )
{
clrscr( );
tri_num a;
a.tri_num::tri_num(5);
}
OUTPUT
Triangular number : 15
Explanation: In the above program, class tri_num is declared with private integer f and member
function sum( ). The class also has zero-argument constructor and one–argument constructor.
}
};
text t; // Global object
void main( )
Object Oriented Programming and C++
{ }
Local Variables:
Variables that are declared inside a function or block are local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own.
Following is the example using local variables:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables:
Global variables are defined outside of all the functions, usually on top of the program. The
global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration. Following is the example using global
and local variables:
#include <iostream>
using namespace std;
// Global variable declaration:
Object Oriented Programming and C++
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable
inside a function will take preference. For example:
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result:
10
QUESTIONS
SECTION-A
1. Define bitfields.
2. What do you meant by overloading a function? When do we use this concept?
3. What is a class? How does it accomplish datahiding?
4. Define Local class?
5. With objects we can access the public members of a class using ___________. \
6. A class can have both ______ and _______ as members.
7. Define inline function?
8. Define Function Overloading?
Object Oriented Programming and C++
SECTION-B
1. Write short notes on memory allocation for objects?
2. Write short notes on returning objects?
3. Write a Sample program using friend function?
4. Write short notes on static member function?
5. Describe about static data mebers?
6. Write short notes on defining member function?
7. Describe about Inline function with examples?
8. Write short notes on function prototypes with examples?
9. Write short notes on Call by reference and Return by reference?
10. Describe about friend function with examples?
SECTION-C
1. Write in detail about friendly functions with example program?
2. Explain bit fields with example?
3. Explain the concepts of function prototypes with examples?
4. Explain about Inline function with examples?
5. Explain about static data members with a sample program?
6. Write in detail about functions and function prototyping in c++?
7. Explain about friend functions and its characteristics with example program?
8. Explain about function overloading with sample program?
9. Write in detail about virtual functions with sample program?
10. Explain about private member function with examples?
INTRODUCTION
Operator overloading is an important and useful feature of C++. The concept of operator
overloading is quite similar to that of function overloading.
An operator is a symbol that indicates an operation. It is used to perform operation with
constants and variables. Without an operator, programmer cannot built an expression.
Object Oriented Programming and C++
C++ frequently uses user-defined data types, which is a combination of one or more basic
data types. C++ has an ability to treat user-defined data type like the one they were built-in type.
User-defined data types created from class or struct are nothing but combination of one or more
variables of basic data types. The compiler knows how to perform various operations using
operators for built-in types; however, for the objects those are instance of the class, the operation
routine must be defined by the programmer.
b=k;
c=m;
d=l;
}
void show(void);
void operator ++( );
};
void num :: show( )
{
cout <<" A= "<<a <<" B= " <<b <<" C = "<<c <<" D = "<<d;
}
void num :: operator ++( )
{
++a; ++b; ++c; ++d;
}
main( )
{
clrscr( );
num X(3,2,5,7);
cout <<"\n Before Increment of X : ";
X.show( );
++X;
cout <<"\n After Increment of X : ";
X.show( );
return 0;
}
{
clrscr( );
plusplus p1, p2;
cout <<"\n p1 = "<<p1.getnum( );
cout <<"\n p2 = "<<p2.getnum( );
p1=p2++;
cout <<endl<<" p1 = "<<p1.getnum( );
cout <<endl<<" p2 = "<<p2.getnum( );
p1++;
// p1++=2;
cout <<endl<<" p1 = "<<p1.getnum( );
cout <<endl<<" p2 = "<<p2.getnum( );
}
++T1; // increment T1
T1.displayTime(); // display T1
++T1; // increment T1 again
T1.displayTime(); // display T1
T2++; // increment T2
T2.displayTime(); // display T2
T2++; // increment T2 again
T2.displayTime(); // display T2
return 0;
}
When the above code is compiled and executed, it produces the following result:
H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
If overloaded as a member function they require one argument. The argument contains value
of the object, which is to the right of the operator. If we want to perform the addition of two
objects o1 and o2, the overloading function should be declared as follows:
operator (num o2);
Where, num is a class name and o2 is an object.
To call function operator the statement is as follows:
o3=o1+o2;
We know that a member function can be called by using class of that object. Hence, the called
member function is always preceded by the object. Here, in the above statement, the
object o1 invokes the function operator ( ) and the object o2 is used as an argument for the
function.
TYPE CONVERSION
Implicit conversions are automatically performed when a value is copied to a compatible
type. For example:
short a=2000;
int b;
b=a;
Here, the value of a is promoted from short to int without the need of any explicit operator.
This is known as a standard conversion. Standard conversions affect fundamental data types, and
allow the conversions between numerical types (short to int, int to float, double to int...), to or
from bool, and some pointer conversions.
Converting to int from some smaller integer type, or to double from float is known as
promotion, and is guaranteed to produce the exact same value in the destination type. Other
conversions between arithmetic types may not always be able to represent the same value
exactly:
If a negative integer value is converted to an unsigned type, the resulting value
corresponds to its 2's complement bitwise representation (i.e., -1 becomes the largest
value represent able by the type, -2 the second largest, ...).
The conversions from/to bool consider false equivalent to zero (for numeric types) and
to null pointer (for pointer types); true is equivalent to all other values and is converted
to the equivalent of 1.
Object Oriented Programming and C++
If the conversion is from a floating-point type to an integer type, the value is truncated
(the decimal part is removed). If the result lies outside the range of representable values
by the type, the conversion causes undefined behavior.
if the conversion is between numeric types of the same kind (integer-to-integer or
floating-to-floating), the conversion is valid, but the value is implementation-specific
(and may not be portable).
Some of these conversions may imply a loss of precision, which the compiler can signal
with a warning. This warning can be avoided with an explicit conversion.
For non-fundamental types, arrays and functions implicitly convert to pointers, and pointers
in general allow the following conversions:
Null pointers can be converted to pointers of any type
Pointers to any type can be converted to void pointers.
Pointer upcast: pointers to a derived class can be converted to a pointer of an accessible
and unambiguous base class, without modifying its const or volatile qualification.
Implicit conversions with classes
In the world of classes, implicit conversions can be controlled by means of three member
functions:
Single-argument constructors: allow implicit conversion from a particular type to initialize an
object.
Assignment operator: allow implicit conversion from a particular type on assignments.
Type-cast operator: allow implicit conversion to a particular type.
For example:
// implicit conversion of classes:
#include <iostream>
using namespace std;
class A {};
class B
{
public:
// conversion from A (constructor):
B (const A& x) {}
// conversion from A (assignment):
B& operator= (const A& x) {return *this;}
// conversion to A (type-cast operator)
operator A() {return A();}
};
int main ()
{
A foo;
B bar = foo; // calls constructor
bar = foo; // calls assignment
foo = bar; // calls type-cast operator
return 0;
}
The type-cast operator uses a particular syntax: it uses the operator keyword followed by the
destination type and an empty set of parentheses. Notice that the return type is the destination
type and thus is not specified before the operator keyword.
When constants and variables of various data types are clubbed in a single expression,
automatic type conversion takes place. This is so for basic data types. The compiler has no idea
about the user-defined data types and about their conversion to other data types. The programmer
should write the routines that convert basic data types to user-defined data types or vice versa.
There are three possibilities of data conversion as given below:
Object Oriented Programming and C++
Conversion from basic data type to user-defined data type (class type).
Conversion from class type to basic data type.
Conversion from one class type to another class type.
Conversion from Basic to Class Type
The conversion from basic to class type is easily carried out. It is automatically done by the
compiler with the help of in-built routines or by applying typecasting. In this type the left-hand
operand of = sign is always class type and right-hand operand is always basic type. The program
given below explains the conversion from basic to class type.
INTRODUCTION
Object Oriented Programming and C++
};
void main( )
{
clrscr( );
B b; // DECLARATION OF OBJECT
b.show( );
}
TYPES OF INHERITANCES
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the base class, and the new class is referred to as the
derived class.
Base & Derived Classes:
A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class derivation list to
specify the base class(es). A class derivation list names one or more base classes and has the
form
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a
previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
Object Oriented Programming and C++
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
Access Control and Inheritance:
A derived class can access all the non-private members of its base class. Thus base-class
members that should not be accessible to the member functions of derived classes should be
declared private in the base class.
We can summarize the different access types according to who can access them in the
following way:
Table:Access Control
A derived class inherits all base class methods with the following exceptions:
The process of inheritance can be a simple one or may be complex. This depends on the
following points:
(1) Number of base classes: The program can use one or more base classes to derive a single
class.
(2) Nested derivation: The derived class can be used as base class and new class can be derived
from it. This can be possible to any extent.
Depending on the above points inheritance is classified as follows:
• Single Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Multilevel Inheritance
• Hybrid Inheritance
• Multi-path Inheritance
Object Oriented Programming and C++
The different types of inheritance are described.The base classes are at the top level and
derived classes at the bottom. The arrow pointed from top to bottom indicates that properties of
base classes are inherited by the derived class and the reverse is not applicable.
SINGLE INHERITANCE
When only one class is derived from a single base class such derivation of a class is known as
single inheritance, further, the derived class is not used as a base class. This type of inheritance
uses one base and one derived class.
The new class is termed as derived class and the old class is called as base class . A derived
class inherits data member variables and functions of base class. However, constructors and
destructors of base class are not inherited in derived class.
The newly created class receives entire characteristics from its base class. In single
inheritance, there are only one base class and derived class. The single inheritance is not as
complicated as compared to other types of inheritances.
Program fo Payroll system using single inheritance
#include<iostream.h>
#include<conio.h>
class emp
{
public:
int eno;
char name[20],des[20];
void get()
{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
};
class salary:public emp
{
float bp,hra,da,pf,np;
public:
void get1()
{
cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
Object Oriented Programming and C++
void display()
{
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<n
p<<"\n";
}
};
void main()
{
int i,n;
char ch;
salary s[10];
clrscr();
cout<<"Enter the number of employee:";
cin>>n;
for(i=0;i<n;i++)
{
s[i].get();
s[i].get1();
s[i].calculate();
}
cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for(i=0;i<n;i++)
{
s[i].display();
}
getch();
}
Output:
Enter the Number of employee:1
Enter the employee No: 150
Enter the employee Name: ram
Enter the designation: Manager
Enter the basic pay: 5000
Enter the HR allowance: 1000
Enter the Dearness allowance: 500
Enter the profitability Fund: 300
MULTILEVEL INHERITANCE
The procedure of deriving a class from derived class is named as multilevel inheritance.
Fig.Multilevel inheritance
In the figure class A3 is derived from class A2. The class A2 is derived from class A1. The
classA3 is derived class. The class A2 is a derived class as well as base class for class A3. The
class A2is called as intermediate base class. The class A1 is a base class of classes A2 and A3.
The series of classes A1, A2, and A3 is called as inheritance pathway.
Write a program to create multilevel inheritance. Create classes A1, A2, and A3.
// Multilevel inheritance //
# include <iostream.h>
# include <constream.h>
class A1 // Base class
{
protected :
char name[15];
int age;
};
class A2 : public A1 // Derivation first level
{
protected :
float height;
float weight;
};
class A3 : public A2 // Derivation second level
{
protected :
char sex;
public :
void get( ) // Reads data
{
cout <<"Name : "; cin >>name;
cout <<"Age : "; cin >>age;
cout <<"Sex : "; cin >>sex;
cout <<"Height : "; cin >>height;
cout <<"Weight : "; cin >>weight;
}
void show( ) // Displays data
{
cout <<"\nName : " <<name;
cout <<"\nAge : " <<age <<" Years";
Object Oriented Programming and C++
In C++ programming, a class be can derived from a derived class which is known as multilevel
inhertiance. For example:
class A
{ .... ... .... };
class B : public A
{ .... ... .... };
class C : public B
{ .... ... .... };
In this example, class B is derived from class A and class C is derived from derived class B.
Example to Demonstrate the Multilevel Inheritance
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
Output
Base class content.
Object Oriented Programming and C++
Explanation of Program
In this program, class B is derived from A and C is derived from B. An object of class C is
defined in main( ) function. When the display( ) function is called, display( ) in class A is
executed because there is no display( ) function in C and B. The program first looks for
display( ) in class C first but, can't find it. Then, looks in B because C is derived from B. Again it
can't find it. And finally looks it in A and executes the codes inside that function.
If there was display( ) function in C too, then it would have override display( ) in A because of
member function overriding.
MULTIPLE INHERITANCE
Multiple inheritances is the latest addition to the C++ language. When a class is derived from
more than one class then this type of inheritance is called as multiple inheritances. A class can
be derived by inheriting properties of more than one class. Properties of various pre-defined
classes are transferred to single derived class. The below diagram shows multiple inheritances.
Fig.Mutiple Inhertance
PROGRAM:
#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()
{
Object Oriented Programming and C++
}
};
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
In C++ programming, a class can be derived from more than one parents. For example: A
class Rectangle is derived from base classes Area and Circle.
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};
/* Rectangle class is derived from classes Area and Perimeter. */
class Rectangle : private Area, private Perimeter
{
private:
float length, breadth;
public:
Rectangle() : length(0.0), breadth(0.0) { }
void get_data( )
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}
float area_calc()
{
/* Calls area_calc() of class Area and returns it. */
return Area::area_calc(length,breadth);
}
float peri_calc()
{
/* Calls peri_calc() function of class Perimeter and returns it. */
return Perimeter::peri_calc(length,breadth);
}
};
int main()
{
Rectangle r;
r.get_data();
cout<<"Area = "<<r.area_calc();
cout<<"\nPerimeter = "<<r.peri_calc();
return 0;
}
Output
Enter length: 5.1
Enter breadth: 2.3
Area = 11.73
Perimeter = 14.8
HIERARCHICAL INHERITANCE
We know that in inheritance, one class could be inherited from one or more classes. In
addition, new members are added to the derived class. Inheritance also supports hierarchical
arrangement of programs. Several programs require hierarchical arrangement of classes, in
which derived classes share the properties of base class. Hierarchical unit shows top down style
Object Oriented Programming and C++
through splitting a compound class into several simple sub classes. The program based on
hierarchical inheritance is illustrated below.
Write a program to show hierarchical inheritance.
# include <constream.h>
# include <iostream.h>
class red
{
public:
red ( ) {cout<<" Red ";};
};
class yellow
{
public :
yellow( ) { cout <<" Yellow "; }
};
class blue
{
public:
blue ( ) { cout <<" Blue "; }
};
class orange : public red, public yellow
{
public :
orange( )
{
cout <<" = Orange ";
}
};
class green : public blue, public yellow
{
public:
green( )
{
cout <<" = Green ";
}
};
class violet : public red, public blue
{
public:
violet( ) { cout <<" = Violet "; }
};
Hierarchical Inheritance is a method of inheritance where one or more derived classes is derived
from common base class.
Example:
#include <iostream.h>
class Side
{
protected:
int l;
public:
void set_values (int x)
{ l=x;}
};
class Square: public Side
{
public:
int sq()
{ return (l *l); }
};
class Cube:public Side
{
public:
int cub()
{ return (l *l*l); }
};
int main ()
{
Square s;
s.set_values (10);
cout << "The square value is::" << s.sq() << endl;
Cube c;
c.set_values (20);
cout << "The cube value is::" << c.cub() << endl;
return 0;
}
Object Oriented Programming and C++
Result:
The square value is:: 100
The cube value is::8000
In the above example the two derived classes "Square", "Cube" uses a single base class "Side".
Thus two classes are inherited from a single class. This is the hierarchical inheritance OOP's
concept in C++.
HYBRID INHERITANCE
The combination of one or more types of inheritance is known as hybrid inheritance.
Sometimes, it is essential to derive a class using more types of inheritances. In the diagram
given below the class GAME is derived from two base classes
i.e., LOCATION and PHYSIQUE. The class PHYSIQUE is also derived from class player.
{
cout <<" Enter Following Information\n";
cout <<"Name : "; cin>> name;
cout <<"Gender : "; cin>>gender;
cout <<"Age : "; cin>>age;
cout <<"Height : "; cin>>height;
cout <<"Weight : "; cin>>weight;
cout <<"City : "; cin>>city;
cout <<"Pincode : "; cin>>pin;
cout <<"Game : "; cin>>game;
}
void show( )
{
cout <<"\n Entered Information";
cout <<"\nName : "; cout<<name;
cout <<"\nGender : "; cout<<gender;
cout <<"\nAge : "; cout<<age;
cout <<"\nHeight : "; cout<<height;
cout <<"\nWeight : "; cout<<weight;
cout <<"\nCity : "; cout<<city;
cout <<"\nPincode : "; cout<<pin;
cout <<"\nGa....
}
"Hybrid Inheritance" is a method where one or more types of inheritance are combined together
and used.
Example:
#include <iostream.h>
class mm
{
protected:
int rollno;
public:
void get_num(int a)
{ rollno = a; }
void put_num()
{ cout << "Roll Number Is:"<< rollno << "\n"; }
};
class marks : public mm
{
protected:
int sub1;
int sub2;
public:
void get_marks(int x,int y)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
Object Oriented Programming and C++
}
};
class extra
{
protected:
float e;
public:
void get_extra(float s)
{e=s;}
void put_extra(void)
{ cout << "Extra Score::" << e << "\n";}
};
class res : public marks, public extra{
protected:
float tot;
public:
void disp(void)
{
tot = sub1+sub2+e;
put_num();
put_marks();
put_extra();
cout << "Total:"<< tot;
}
};
int main()
{
res std1;
std1.get_num(10);
std1.get_marks(10,20);
std1.get_extra(33.12);
std1.disp();
return 0;
}
Result:
Roll Number Is: 10
Subject 1: 10
Subject 2: 20
Extra score:33.12
Total: 63.12
In the above example the derived class "res" uses the function "put_num()". Here the
"put_num()" function is derived first to class "marks". Then it is deriived and used in class "res".
This is an example of "multilevel inheritance-OOP's concept". But the class "extra" is inherited a
single time in the class "res", an example for "Single Inheritance". Since this code uses both
"multilevel" and "single" inheritence it is an example of "Hybrid Inheritance".
MULTIPATH INHERITANCE
When a class is derived from two or more classes, which are derived from the same base class
such type of inheritance is known as multipath inheritance. Multipath inheritance consists of
many types of inheritances such as multiple, multilevel and hierarchical as shown in Figure 9.11.
Consider the following example:
Object Oriented Programming and C++
class A1
{
protected:
int a1;
};
class A2 : public A1
{
protected:
int a2;
};
class A3: public A1
{
protected: int a3;
};
class A4: public A2,A3
{int a4; };
Ambiguity in classes
In the given example, class A2 and A3 are derived from the same base class i.e.,
class A1(hierarchical inheritance). The classes A2 and A3 both can access variable a1 of
class A1. The class A4 is derived from class A2 and class A3 by multiple inheritances. If we try
to access the variable a1 of class A, the compiler shows error messages as given below.
protected:
int a3;
};
class A4: public A2,A3
{
int a4;
};
When classes are declared as virtual, the compiler takes necessary precaution to avoid
duplication of member variables. Thus, we make a class virtual if it is a base class that has been
used by more than one derived class as their base class.
Example program to show the virtual base class
#include<iostream.h>
#include<conio.h>
class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"\n\n\tRoll No:"<<rno<<"\n";
}
};
public:
int part1,part2;
void getmarks()
{
cout<<"Enter Marks\n";
cout<<"Part1:";
cin>>part1;
cout<<"Part2:";
cin>>part2;
}
void putmarks()
{
cout<<"\tMarks Obtained\n";
cout<<"\n\tPart1:"<<part1;
cout<<"\n\tPart2:"<<part2;
}
};
public:
int score;
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"\n\tSports Score is:"<<score;
}
};
void main()
{
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Output:
Enter Roll No: 200
Enter Marks
Part1: 90
Part2: 80
Enter Sports Score: 80
When two or more objects are derived from a common base class, we can prevent multiple
copies of the base class being present in an object derived from those objects by declaring the
base class as virtual when it is being inherited. Such a base class is known as virtual base class.
This can be achieved by preceding the base class’ name with the word virtual.
ABSTRACT CLASSES
When a class is not used for creating objects it is called as abstract class. The abstract class
can act as a base class only. It is a lay out abstraction in a program and it allows a base on which
several levels of inheritance can be created. The base classes act as foundation of class hierarchy.
An abstract class is developed only to act as a base class and to inherit and no objects of these
classes are declared. An abstract class gives a skeleton or structure, using which other classes is
shaped. The abstract class is central and generally present at the starting of the hierarchy.
The hierarchy of classes means chain or groups of classes being involved with one another. In
the last program, class A is an abstract class because no instance (object) of class A is declared.
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes
are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they will also become abstract class.
Object Oriented Programming and C++
ADVANTAGES OF INHERITANCE
The most frequent use of inheritance is for deriving classes using existing classes, which
provides reusability. The existing classes remain unchanged. By reusability, the
development time of software is reduced.
The derived classes extend the properties of base classes to generate more dominant
object.
The same base classes can be used by a number of derived classes in class hierarchy.
When a class is derived from more than one class, all the derived classes have the same
properties as that of base classes.
DISADVANTAGES OF INHERITANCE
Though object-oriented programming is frequently propagandized as an answer for
complicated projects, inappropriate use of inheritance makes a program more
complicated.
Invoking member functions using objects create more compiler overheads.
Object Oriented Programming and C++
In class hierarchy various data elements remain unused, the memory allocated to them is
not utilized.
INTRODUCTION
Most of the learners feel that pointer is a puzzling topic. However, pointers can make
programs quicker, straightforward and memory efficient. C/C++ gives more importance to
pointers. Hence, it is important to know the operation and applications of pointers. Pointers are
used as tool in C/C++.
Like C, in C++ variables are used to hold data values during program execution. Every
variable when declared occupies certain memory locations. It is possible to access and display
the address of memory location of variables using ‘&’ operator. Memory is arranged in series of
bytes. These series of bytes are numbered from zero onwards. The number specified to a cell is
known as memory address. Pointer variable stores the memory address of any type of variable.
The pointer variable and normal variable should be of the same type. The pointer is denoted by
(*) asterisk symbol.
POINTER DECLARATION
Pointer variables can be declared as below:
Example
int *x;
float *f;
char *y;
In the first statement ‘x’ is an integer pointer and it informs to the compiler that it holds
the address of any integer variable. In the same way, ‘f’ is a float pointer that stores the
address of any float variable and ‘y’ is a character pointer that stores the address of any
character variable.
The indirection operator (*) is also called the deference operator. When a pointer is
dereferenced, the value at that address stored by the pointer is retrieved.
Normal variable provides direct access to their own values whereas a pointer indirectly
accesses the value of a variable to which it points.
The indirection operator (*) is used in two distinct ways with pointers, declaration and
deference.
C++ pointers are easy and fun to learn. Some C++ tasks are performed more easily with
pointers, and other C++ tasks, such as dynamic memory allocation, cannot be performed without
them.
As you know every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator which denotes an address in
memory. Consider the following which will print the address of the variables defined:
#include <iostream>
using namespace std;
int main ()
{
int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var1 variable: 0xbfebd5c0
Object Oriented Programming and C++
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
Concept Description
C++ supports null pointer, which is a constant with a
C++ Null Pointers
value of zero defined in several standard libraries.
There are four arithmetic operators that can be used on
C++ pointer arithmetic
pointers: ++, --, +, -
There is a close relationship between pointers and arrays.
C++ pointers vs arrays
Let us check how?
C++ array of pointers You can define arrays to hold a number of pointers.
C++ pointer to pointer C++ allows you to have pointer on a pointer and so on.
Passing an argument by reference or by address both
Passing pointers to functions enable the passed argument to be changed in the calling
function by the called function.
C++ allows a function to return a pointer to local variable,
Return pointer from functions
static variable and dynamically allocated memory as well.
POINTER TO CLASS
We know that pointer is a variable that holds the address of another data variable. The variable
may be of any data type i.e., int, float or double. In the same way, we can also define pointer to
class. Here, starting address of the member variables can be accessed. Such pointers are
called class pointers.
Example:
class book
{
char name [25];
char author [25];
int pages;
};
a) class book *ptr;
sor
a) struct book *ptr;
In the above example, *ptr is pointer to class book. Both the statements (a) and (b) are valid.
The syntax for using pointer with member is given below.
1) ptr->name 2) ptr->author 3) ptr->pages.
By executing these three statements, starting address of each member can be estimated.
POINTER TO OBJECT
Like variables, objects also have an address. A pointer can point to specified object. The
following program illustrates this.
Write a program to declare an object and pointer to the class. Invoke member functions
using pointer.
# include <iostream.h>
# include <conio.h>
class Bill
{
int qty;
float price;
float amount;
public :
void getdata (int a, float b, float c)
{
qty=a;
Object Oriented Programming and C++
price=b;
amount=c;
}
void show( )
{
cout <<"Quantity : " <<qty <<"\n";
cout <<"Price : " <<price <<"\n";
cout <<"Amount : " <<amount <<"\n";
}
};
int main( )
{
clrscr( );
Bill s;
Bill *ptr =&s;
ptr->getdata(45,10.25,45*10.25);
(*ptr).show( );
return 0;
}
A variable that holds an address value is called a pointer variable or simply pointer.
Pointer can point to objects as well as to simple data types and arrays.sometimes we dont
know, at the time that we write the program , how many objects we want to create. when this is
the case we can use new to creat objects while the program is running.
new returns a pointer to an unnamed objects. lets see the example of student that will clear
your idea about this topic
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
int rollno;
string name;
public:
student():rollno(0),name("")
{}
student(int r, string n): rollno(r),name (n)
{}
void get()
{
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
}
};
Object Oriented Programming and C++
void main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}
THE this POINTER
Use of this pointer is now outdated. The objects are used to invoke the non-static member
functions of the class. For example, if p is an object of class P and get( ) is a member function of
P, the statement p.get( ) is used to call the function. The statement p.get( ) operates on p.In the
same way if ptr is a pointer to P object, the function called ptr->get( ) operates on *ptr.
However, the quesstion is, how does the member function get ( ) understand which p it is
functioning on? C++ compiler provides get ( ) with a pointer to p called this. The pointer this is
transferred as an unseen parameter in all calls to non-static member functions. The keyword
this is a local variable that is always present in the body of any non-static member function.
Every object in C++ has access to its own address through an important pointer called this
pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a
member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only
member functions have a this pointer.
Example of this pointer
#include <iostream>
using namespace std;
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Object Oriented Programming and C++
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
Working of this
Write a program to declare a pointer to the base class and access the member variable of
base and derived class.
// Pointer to base object //
# include <iostream.h>
# include <conio.h>
class A
{
public :
int b;
void display( )
{
cout <<"b = " <<b <<"\n";
}
};
class B : public A
{
public :
int d;
void display( )
{
cp->display( );
return 0;
}
ARRAYS
Array is a collection of elements of similar data types in which each element is unique and
located in separate memory locations.
C++ provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Array Declaration and Initialization
Declaration of an array is shown below:
int a [5];
It tells to the compiler that ‘a’ is an integer type of array and it must store five integers. The
compiler reserves two bytes of memory for each integer array element. In the same way array of
different data types are declared as below:
Array Declaration
char ch [10];
float real [10];
long num [5];
The array initialization is done as given below:
Array Initialization
int a [5]={1,2,3,4,5};
Here, five elements are stored in an array ‘a’. The array elements are stored sequentially in
separate locations. Then question arises how to call individually to each element from this bunch
of integer elements. Reading of array elements begins from zero.
Example of an array:
#include <iostream>
using namespace std;
void printarray (int arg[], int length)
{
for (int n=0; n<length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}
In the code above, the first parameter (int arg[]) accepts any array whose elements are of
type int, whatever its length. For that reason, we have included a second parameter that tells the
function the length of each array that we pass to it as its first parameter. This allows the for loop
Object Oriented Programming and C++
that prints out the array to know the range to iterate in the array passed, without going out of
range.
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
CHARACTERISTICS OF ARRAYS
The declaration int a[5] is nothing but creation of five variables of integer type in memory.
Instead of declaring five variables for five values, the programmer can define them in an
array.
All the elements of an array share the same name, and they are distinguished from one
another with the help of element number.
The element number in an array plays major role in calling each element.
Any particular element of an array can be modified separately without disturbing other
elements.
int a [5] ={1,2,3,4,8};
If the programmer needs to replace 8 with 10, he/she is not required to change all other
numbers except 8. To carry out this task the statement a[4]=10 can be used. Here the other
three elements are not disturbed.
ARRAYS OF CLASSES
We know that array is a collection of similar data types. In the same way, we can also define
array of classes. In such type of array, every element is of class type. Array of class objects can
be declared as shown below:
class stud
{
public:
char name [12]; // class declaration
int rollno;
char grade[2];
};
class stud st[3]; // declaration of array of class objects
In the above example, st[3] is an array of three elements containing three objects of class stud.
Each element of st[3] has its own set class member variables i.e., char name[12], int
rollno and char grade[2].
Object Oriented Programming and C++
QUESTIONS
SECTION-A
1. A constructor that accepts no parameters is called __________
2. How to overload unary operators using operator overloading?
3. Define copy constructor?
4. How to overload binary operators using operator overloading?
5. What is dynamic constructor?
6. How to declare multiple constructors in a classs?
7. _________ has the same name as that of class.
8. How is dynamic initialization of objects achieved?
9. _________is called compile time polymorphism.
10. ________ and ________ operators are not overloaded in C++.
SECTION-B
1. Describe the importance of constructors?
2. Write a Sample program for multiple constructors?
3. Write a Sample program for overloading a constructors?
4. How is dynamic intialization of objects achieved?
5. How to overload a constructor? Explain it with example program?
6. Write short notes on constructor with example statement?
7. Write short notes on parameterized constructor?
8. Describe about multiple constructor in a class
9. Write short notes on defining operator overloading with syntax?
10. Describe about overloading unary operator using sample program?
SECTION-C
1. Write in detail about overloaded constructors?
2. Explain briefly about dynamic initialization of objects with examples program?
3. Explain about multiple constructors in a class?
4. Explain about passing parameter to a constructor?
5. Write in detail about destructor with a sample program?
6. Explain the concepts of overloading unary operator?
7. Write a sample program to implement multiple constructors in a class?
8. Explain about constructor with default arguments?
9. Write a sample program to implement copy and dynamic constructor?
10. Explain type conversion
Object Oriented Programming and C++
INTRODUCTION
Memory is one of the critical resources of a computer system. One must be conscious about
the memory modules while an application is being developed. In this chapter, we will learn
stack, heap, dynamic object, and calling conventions.
MEMORY MODELS
The memory model sets the supportable size of code and data areas.Before compiling and
linking the source code, we need to specify the appropriate memory model. Using memory
models, we can set the size limits of the data and code. C/C++ programs always use different
segments for code and data. The memory model you opt decides the default method of memory
addressing. The default memory model is small.
Tiny
Use the tiny model when memory is at an absolute premium. All four segment registers (CS,
DS, ES, SS) are initialized with same address and all addressing is accomplished using 16 bits.
Total memory capacity in this case is 64 K bytes. In short, memory capacity is abbreviated as
KB. This means that the code, data, and stack must all fit within the same 64 KB segment.
Programs are executed quickly if this model is selected. Near pointers are always used. Tiny
model programs can be converted to .COM format.
{
cout << "Failed to allocate memory" << endl;
}
*(a+5)=9;
cout << "a[5]=" << *(a+5) << endl;
delete [] a;
delete b;
delete [] c;
return 0;
}
The array a is allocated space for 10 ints but arrays cannot have an initial value. The int
pointer b is allocated space for an int and given an initial value of 89. Next, there is a doomed
attempt to allocate a billion ints on my 1GB RAM PC. As an int takes 4 bytes that would require
4GB. Also under 32 bit Windows you are limited to 2GB of RAM.
The (nothrow) prevents an exception occurring and the failed message is almost certain to be
displayed, unless you are blessed with a 64 Bit computer and a surfeit of RAM.
The array a is tested by setting and displaying an array element. Just as in C, an array and a
pointer can be considered the same-they are addresses. Adding 5 to the pointer is the same as
indexing an array by [5].
Finally the three delete statements free up allocated memory. In the case of the filed c
variable, freeing up a zero pointer is ok.here is following generic syntax to use new operator to
allocate memory dynamically for any data-type.
new data-type;
Here, data-type could be any built-in data type including an array or any user defined data
types include class or structure. Let us start with built-in data types. For example we can define a
pointer to type double and then request that the memory be allocated at execution time. We can
do this using the new operator with the following statements:
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
The memory may not have been allocated successfully, if the free store had been used up. So
it is good practice to check if new operator is returning NULL pointer and take appropriate
action as below:
double* pvalue = NULL;
if( !(pvalue = new double ))
{
cout << "Error: out of memory." <<endl;
exit(1);
}
The malloc() function from C, still exists in C++, but it is recommended to avoid using
malloc() function. The main advantage of new over malloc() is that new doesn't just allocate
memory, it constructs objects which is prime purpose of C++.
At any point, when you feel a variable that has been dynamically allocated is not anymore
required, you can free up the memory that it occupies in the free store with the delete operator as
follows:
delete pvalue; // Release memory pointed to by pvalue
Let us put above concepts and form the following example to show how new and delete work:
#include <iostream>
using namespace std;
int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
Object Oriented Programming and C++
If we compile and run above code, this would produce the following result:
Value of pvalue : 29495
Dynamic Memory Allocation for Arrays:
Consider you want to allocate memory for an array of characters, i.e., string of 20 characters.
Using the same syntax what we have used above we can allocate memory dynamically as shown
below.
char* pvalue = NULL; // Pointer initialized with null
pvalue = new char[20]; // Request memory for the variable
To remove the array that we have just created the statement would look like this:
delete [] pvalue; // Delete array pointed to by pvalue
Following the similar generic syntax of new operator, you can allocat for a multi-dimensional
array as follows:
double** pvalue = NULL; // Pointer initialized with null
pvalue = new double [3][4]; // Allocate memory for a 3x4 array
However, the syntax to release the memory for multi-dimensional array will still remain same
as above:
delete [] pvalue; // Delete array pointed to by pvalue
Dynamic Memory Allocation for Objects:
Objects are no different from simple data types. For example, consider the following code
where we are going to use an array of objects to clarify the concept:
#include <iostream>
using namespace std;
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
};
int main( )
{
Box* myBoxArray = new Box[4];
delete [] myBoxArray; // Delete array
return 0;
}
If you were to allocate an array of four Box objects, the Simple constructor would be called
four times and similarly while deleting these objects, destructor will also be called same number
of times.
If we compile and run above code, this would produce the following result:
Constructor called!
Constructor called!
Constructor called!
Constructor called!
Object Oriented Programming and C++
Destructor called!
Destructor called!
Destructor called!
Destructor called!
DYNAMIC OBJECTS
C++ supports dynamic memory allocation. C++ allocates memory and initializes the member
variables. An object can be created at run-time. Such object is called as dynamic object. The
construction and destruction of dynamic object is explicitly done by the programmer. The
dynamic objects can be created and destroyed by the programmer. The
operator new and delete are used to allocate and deallocate memory to such objects. A dynamic
object can be created using new operator as follows:
ptr= new classname;
The new operator returns the address of object created and it is stored in the pointer ptr. The
variable ptr is a pointer object of the same class. The member variables of object can be accessed
using pointer and -> (arrow) operator.
INTRODUCTION
The word poly means many and morphism means several forms. Both the words are derived
from Greek language. Thus, by combining these two words a whole new word is created called
as polymorphism i.e., various forms. We have learnt overloading of functions and operators. It
is also one-type of polymorphism. The information pertaining to various overloaded member
functions is to be given to the compiler while compiling. This is called as early binding or static
binding. In C++ function can be bound either at compile time or run time. Deciding a function
call at compiler time is called compile time or early or static binding. Deciding function call at
runtime is called as runtime or late or dynamic binding. Dynamic binding permits suspension of
the decision of choosing suitable member functions until run-time.
BINDING IN C++
Though C++ is an object-oriented programming language, it is very much inspired by
procedural language. C++ supports two types of binding, static or early binding and dynamic or
late binding.
Binding refers to the process that is used to convert identifiers (such as variable and function
names) into machine language addresses. Although binding is used for both variables and
functions, in this lesson we’re going to focus on function binding.
In the above program, base and derived classes have the same member function display( ).
This is not an overloaded function because their prototype is same and they are defined in
different classes.
Direct function calls can be resolved using a process known as early binding. Early binding
(also called static binding) means the compiler is able to directly associate the identifier name
(such as a function or variable name) with a machine address. Remember that all functions have
a unique machine address. So when the compiler encounters a function call, it replaces the
function call with a machine language instruction that tells the CPU to jump to the address of the
function.
Simple calculator program that uses early binding:
#include <iostream>
using namespace std;
int Add(int nX, int nY)
{
return nX + nY;
}
int Subtract(int nX, int nY)
{
return nX - nY;
}
int Multiply(int nX, int nY)
{
return nX * nY;
}
int main()
{
int nX;
cout << "Enter a number: ";
cin >> nX;
int nY;
cout << "Enter another number: ";
cin >> nY;
int nOperation;
do
{
cout << "Enter an operation (0=add, 1=subtract, 2=multiply): ";
cin >> nOperation;
} while (nOperation < 0 || nOperation > 2);
int nResult = 0;
switch (nOperation)
{
case 0: nResult = Add(nX, nY); break;
case 1: nResult = Subtract(nX, nY); break;
case 2: nResult = Multiply(nX, nY); break;
}
cout << "The answer is: " << nResult << endl;
return 0;
}
Object Oriented Programming and C++
Because Add(), Subtract(), and Multiply() are all direct function calls, the compiler will use
early binding to resolve the Add(), Subtract(), and Multiply() function calls. The compiler will
replace the Add() function call with an instruction that tells the CPU to jump to the address of the
Add() function. The same holds true for for Subtract() and Multiply().
Late Binding
In some programs, it is not possible to know which function will be called until runtime (when
the program is run). This is known as late binding (or dynamic binding). In C++, one way to get
late binding is to use function pointers. To review function pointers briefly, a function pointer is
a type of pointer that points to a function instead of a variable. The function that a function
pointer points to can be called by using the function call operator (()) on the pointer.
For example, the following code calls the Add() function:
int Add(int nX, int nY)
{
return nX + nY;
}
int main()
{
// Create a function pointer and make it point to the Add function
int (*pFcn)(int, int) = Add;
cout << pFcn(5, 3) << endl; // add 5 + 3
return 0;
}
Late binding is slightly less efficient since it involves an extra level of indirection. With early
binding, the compiler can tell the CPU to jump directly to the function’s address. With late
binding, the program has to read the address held in the pointer and then jump to that address.
This involves one extra step, making it slightly slower. However, the advantage of late binding is
that it is more flexible than early binding, because decisions about what function to call do not
need to be made until run time.
VIRTUAL FUNCTIONS
Virtual functions of base classes must be redefined in the derived classes. The programmer
can define a virtual function in a base class and can use the same function name in any derived
class, even if the number and type of arguments are matching. The matching function overrides
the base class function of the same name. Virtual functions can only be member functions. We
can also declare the functions as given below:
int Base::get(int) and int Derived::get(int) even when they are not virtual.
The base class version is available to derived class objects via scope override. If they are
virtual, only the function associated with the actual type of objects is available. With virtual
functions we cannot alter the function type. If two functions with the same name have different
arguments, C++ compiler considers them as different, and the virtual function mechanism is
dropped.
By default, C++ matches a function call with the correct function definition at compile time.
This is called static binding. You can specify that the compiler match a function call with the
correct function definition at run time; this is called dynamic binding. You declare a function
with the keyword virtual if you want the compiler to use dynamic binding for that specific
function.
The following examples demonstrate the differences between static and dynamic binding. The
first example demonstrates static binding:
#include <iostream>
using namespace std;
struct A {
void f() { cout << "Class A" << endl; }
};
struct B: A {
void f()
{
cout << "Class B" << endl; }
};
void g(A& arg)
{
arg.f();
}
int main() {
B x;
g(x);
}
The following is the output of the above example:
Class A
The prototype of virtual functions in base and derived classes should be exactly the same.
In case of mismatch, the compiler neglects the virtual function mechanism and treats them
as overloaded functions.
ARRAY OF POINTERS
Polymorphism refers to late or dynamic binding i.e., selection of an entity is decided at run-
time. In class hierarchy, same method names can be defined that perform different tasks, and
then the selection of appropriate method is done using dynamic binding. Dynamic binding is
associated with object pointers. Thus, address of different objects can be stored in an array to
invoke function dynamically. The following program explains this concept.
Following is the declaration of an array of pointers to an integer:
int *ptr[MAX];
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a
pointer to an int value. Following example makes use of three integers which will be stored in an
array of pointers as follows:
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
Write a program to create an array of pointers. Invoke functions using array objects.
# include <iostream.h>
# include <constream.h>
class A
{
public:
virtual void show( )
{
cout <<"A\n";
}
Object Oriented Programming and C++
};
class B : public A
{
public :
void show( )
{ cout <<"B\n"; }
};
class C : public A
{
public :
void show( )
{
cout <<"C\n";
}
};
class D : public A
{
public:
void show( )
{
cout <<"D\n" ;
}
};
class E : public A {
public :
void show( )
{
cout <<"E";
}
};
void main( )
{
clrscr( );
A a;
B b;
C c;
D d;
E e;
A *pa[] = {&a,&b,&c,&d,&e };
for ( int j=0;j<5;j++)
pa[j]->show( );
}
Normally pure virtual functions are defined with null-body. This is so because derived classes
should be able to override them. Any normal function cannot be declared as pure function. After
declaration of pure function in a class, the class becomes abstract class. It cannot be used to
declare any object. Any attempt to declare an object will result in an error “cannot create
instance of abstract class”.
ABSTRACT CLASSES
Abstract classes are like skeleton upon which new classes are designed to assemble well-
designed class hierarchy. The set of well-tested abstract classes can be used and the programmer
only extends them. Abstract classes containing virtual function can be used as help in program
debugging. When various programmers work on the same project, it is necessary to create a
common abstract base class for them. The programmers are restricted to create new base classes.
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes
are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they will also become abstract class.
Characteristics of Abstract Class
Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can
be created.
Abstract class can have normal functions and variables along with a pure virtual function.
Abstract classes are mainly used for Upcasting, so that its derived classes can use its
interface.
Classes inheriting an Abstract Class must implement all pure virtual functions, or else they
will become Abstract too.
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
Output : Implementation of Virtual Function in Derived class
Object Oriented Programming and C++
In the above example Base class is abstract, with pure virtual show() function, hence we cannot
create object of base class.
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Object Oriented Programming and C++
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total Rectangle area: 35
Total Triangle area: 17
The development of such software can be demonstrated by creating a header file. The
fileabstract. h is an example of file containing abstract base class used for debugging purpose.
Contents of file abstract.h is as follows:
Contents of abstract.h header file
# include <iostream.h>
struct debug
{
virtual void show ( )
{
cout<<"\n No function show ( ) defined for this class";
}
};
OBJECT SLICING
Virtual functions permit us to manipulate both base and derived objects using same
member functions with no modifications. Virtual function can be invoked using pointer or
reference. If we do so, object slicing takes place. The following program takes you to the real
thing.
{
B::joy( ) ;
cout <<" \n In class D";
cout <<endl<<" k= "<<k;
}
};
void main( )
{
clrscr( );
B b(3);
D d (4,5 );
B &r=d;
cout <<" \n Using Object ";
d.joy( );
cout <<" \n Using Reference ";
r.joy( );
}
B b(4);
D d(5,2);
}
VIRTUAL DESTRUCTORS
We know how virtual functions are declared. Likewise, destructors can be declared as virtual.
The constructor cannot be virtual, since it requires information about the accurate type of the
object in order to construct it properly. The virtual destructors are implemented in the way like
virtual functions. In constructors and destructors pecking order (hierarchy) of base and derived
classes is constructed. Destructors of derived and base classes are called when a derived class
object addressed by the base class pointer is deleted.
For example, a derived class object is constructed using new operator. The base class pointer
object holds the address of the derived object. When the base class pointer is destroyed using
delete operator, the destructor of base and derived classes is executed.
In C++ a destructor is generally used to deallocate memory and do some other cleanup for a
class object and it’s class members whenever an object is destroyed. Destructors are
distinguished by the tilde, the ‘~’ that appears in front of the destructor name. In order to define a
virtual destructor, all you have to do is simply add the keyword “virtual” before the tilde symbol.
The need for virtual destructors in C++ is best illustrated by some examples. Let’s start by
going through an example that does not use virtual destructors, and then we will go through an
example that does use virtual destructors. Once you see the difference, you will understand why
virtual destructors are needed.
}
void joy( ) { cout <<endl<<" in joy( ) of class D";
}
};
void main( ) {
clrscr( );
D X;
Object Oriented Programming and C++
}
OUTPUT
in joy() of class D in virtual destructor
QUESTIONS
UNIT-II
SECTION-A
1. The concept of reusability is achieved in c++ using_________.
2. Whats the differnce between base class and derived class?
3. Define array?
4. Define pointer?
5. List out the various visibility mode for a class?
6. What is the difference between private and protected?
7. What is an abtract class?
8. What is a virtual base class?
9. Define Containership?
10. .___________ member of a class cannot be inherited either in public mode or in private
mode.
Object Oriented Programming and C++
SECTION-B
1. Write short notes on abstract classes?
2. Write short notes on array with example?
3. Write short notes on Member classes?
4. Write a Sample program to implement pointer declaration?
5. Write a Sample program to implement abstract classes?
6. Write short notes on making a private member inheritable?
7. Write short notes on nesting of classes?
8. Write a Sample program to implement multiple inheritance?
9. Write a Sample program to implement nesting of classes?
10. Write short notes on defining derived classes?
SECTION-C
1. Explain about member classes with a sample program?
2. Explain implementing nesting of classes with a sample program?
3. Explain the various forms of inheritance? Give an example for each
4. Explain single inheritance with a sample program?
5. Write in detail about constructors in derived classes with a sample program?
6. Explain about pointer to class with an example?
7. Explain about object slicing with example
8. Describe pointer to object ?
9. Explain about virtual base classes with a sample program?
10. Describe array of class with example?
Object Oriented Programming and C++
INTRODUCTION
With the advancement of information technology a great amount of information is available
on Internet. Huge amount of data is processed in computer networking. The information can be
uploaded or downloaded from the desktop computer. The information transfer in computer
networking in day-to-day life is in the form of files. The files can be written, read, or updated
depending upon the applications. The data is saved in the file on the disk. The file is an
accumulation of data stored on the disk. The stored data can be retrieved or updated. The console
I/O function reads data through input devices and displays on the screen.
The data read through these functions are temporarily stored in variables or in arrays. The
data stored vanishes when the program ends. In order to store the data permanently, we need to
apply disk I/O function. The disk I/O functions are associated with disk files. These functions
perform read and write operations with the file. Like other languages, C++ also provides
function that allows a programmer to perform read/write operation with the file. The disk I/O
functions in C++ are very different as compared to C, though the entire disk I/O functions of C
can be used in C++. However, these functions are not appropriate with the object-oriented
conditions.
overloaded extraction operators (>>) are defined in the istream class. The functions put( ),
write( ) and overloaded insertion operators (<<) are defined in the ostream class.
C++ provides the following classes to perform output and input of characters to/from files:
These classes are derived directly or indirectly from the classes istream and ostream. We have
already used objects whose types were these classes: cin is an object of class istream and cout is
an object of class ostream. Therefore, we have already been using classes that are related to our
file streams. And in fact, we can use our file streams the same way we are already used to use cin
and cout, with the only difference that we have to associate these streams with physical files.
Example:
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
[file example.txt]
Writing this to a file.
This code creates a file called example.txt and inserts a sentence into it in the same way we are
used to do with cout, but using the file stream myfile instead.
In previous examples we have learnt how to open files using constructor and open( ) function
by using the objects of ifstream and ofstream classes. The opening of file also involves several
modes depending upon operation to be carried out with the file. The open( ) function has two
arguments as given below:
Syntax of open ( ) function
object.open ( “file_ name”, mode);
Here object is a stream object, followed by open ( ) function. The bracket of open function
contains two parameters. The first parameter is name of the file and second is mode in which file
is to be opened. In the absence of mode parameter default parameter is considered. The file mode
parameters are given in table.
File modes
member
stands for access
constant
File open for reading: the internal stream buffer supports input
in input
operations.
File open for writing: the internal stream buffer supports output
out output
operations.
binary binary Operations are performed in binary mode rather than text.
ate at end The output position starts at the end of the file.
All output operations happen at the end of the file, appending to its
app append
existing contents.
trunc truncate Any contents that existed in the file before it is open are discarded.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
Opening a File:
Object Oriented Programming and C++
A file must be opened before you can read from it or write to it. Either the ofstream or fstream
object may be used to open a file for writing and ifstream object is used to open a file for reading
purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream,
and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file should be
opened.
You can combine two or more of these values by ORing them together. For example if you
want to open a file in write mode and want to truncate it in case it already exists, following will
be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File:
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File:
You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard. The only difference is that
you use an ifstream or fstream object instead of the cin object.
Read & Write Example:
Following is the C++ program which opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the program reads information from the
file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
Object Oriented Programming and C++
char data[100];
When the above code is compiled and executed, it produces the following sample input
and output:
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
file we need to update the data files with latest information. To update a particular record of data
file it may be stored anywhere in the file but it is necessary to obtain at which location (in terms
of byte number) the data object is stored.
The sizeof( ) operator determines the size of object. Consider the following statements.
(a) int size=sizeof(o);
Where, o is an object and size is an integer variable. The sizeof( ) operator returns the size of
object o in bytes and it is stored in the variable size. Here, one object is equal to one record.
move to the 28th byte before end of the file
Random file access is done by manipulating the file pointer using the seekg() function (for input)
and seekp() function (for output). In case you are wondering, the g stands for “get” and the p for
“put”.
The seekg() and seekp() functions take two parameters. The first parameter is an offset that
determines how many bytes to move the file pointer. The second parameter is an Ios flag that
specifies what the offset parameter should be offset from.
Input File:
This is line 1
This is line 2
This is line 3
This is line 4
ifstream inf("Sample.dat");
return 0;
}
This prints:
64
which is how long sample.dat is in bytes (assuming a carriage return after the last line).
INTRODUCTION
Template is one of the most useful characteristics of C++. Few old compilers do not allow
template mechanism. Templates are part of ANSI C++ standard. All major compilers support
templates in their new versions. Instantiation is the activity of creating particular type using
templates. The specific classes are known as instance of the template. The template provides
generic programming by defining generic classes. In templates, generic data types are used as
arguments and they can handle a variety of data types. A function that works for all C++ data
types is called as generic function. Templates help the programmer to declare group of
functions or classes. When used with functions they are called function templates. For example,
we can create a template for function square( ).
It helps us to calculate square of a number of any data type including int, float,
long, and double. The templates associated with classes are called as class templates. A template
is almost same as macro and it is type-secured. The difference between template and macro is
illustrated in Section 14.16.
NEED OF TEMPLATE
Template is a technique that allows using a single function or class to work with different
data types. Using template we can create a single function that can process any type of data i.e.,
the formal arguments of template functions are of template (generic) type. They can accept data
of any type such as int, float, long etc. Thus, a single function can be used to accept values of
different data types. Normally, we overload function when we need to handle different data
Object Oriented Programming and C++
types. This approach increases the program size. The disadvantages are that not only program
length is increased but also more local variables are created in the memory.
Template safely overcomes all the limitations occurring while overloading function and
allows better flexibility to the program. The portability provided by a template mechanism can
be extended to classes. The following sections describe use of template in different concepts of
C++ programming. Let us understand the process of declaration of a template.
int i[]={3,5,2,6,8,9,3};
float f[]={3.1,5.8,2.5,6.8,1.2,9.2,4.7};
data <int,float> h;
for (int m=0;m<7;m++)
h.show(i[m],f[m]);
return 0;
}
# include <iostream.h>
# include <conio.h>
# include <process.h>
# include <stdlib.h>
# include <assert.h>
template <class O>
void display (O d)
{
cout<<(float) (rand( )%(d*d))<<"\n";
// if (d==1) exit(1);
assert(d!=1);
display(--d);
void main ( )
{
int x=10;
clrscr( ),
display(x);
}
OUTPUT
46
49
38
12
28
17
11
7
0
0
Assertion failed: d!=1, file REC_TEMP.CPP, line 14
Abnormal program termination
Explanation:The template function generates random number and displays it each time when the
functiondisplay( ) is invoked. The function rand( ) defined instdlib.h is used. The function calls
itself recursively until the value of dbecomes 1. Theassert( )statement checks the value of d and
terminates the program when condition is satisfied. Theassert( ) is defined inassert.h. We can
also use ifstatement followed by exit( )statement as given in comment statement.
Write a program to overload +operator for performing addition of two template based
class objects.
# include <iostream.h>
# include <conio.h>
template <class T>
class num
Object Oriented Programming and C++
{
private :
T number;
public:
num ( ) { number=0; }
void input( )
{
cout <<"\n Enter a number : ";
cin>>number;
}
num operator +(num);
void show( ) { cout <<number; }
};
template <class T>
num <T> num <T> :: operator + (num <T> c)
{
num <T> tmp;
tmp.number=number+c.number;
return (tmp);
}
void main( )
{
clrscr( );
num <int> n1,n2,n3;
n1.input( );
n2.input( );
n3=n1+n2;
cout <<"\n\t n3 = ";
n3.show( );
}
The template characteristics of the base class can be omitted by declaring the type while
deriving the class. All the template-based variables are substituted with basic data types. The
following declaration illustrates derivation of a class using template featured base class.
QUICK SORT USING FUNCTION TEMPLATE
A non-template function is not related to a function template, even though the non-template
function may have the same name and parameter profile as those of a specialization generated
from a template. A non-template function is never considered to be a specialization of a function
template.
The following example implements the QuickSort algorithm with a function template named
quicksort:
#include <iostream>
#include <cstdlib>
using namespace std;
template<class T> void quicksort(T a[], const int& leftarg, const int& rightarg)
{
if (leftarg < rightarg)
{
T pivotvalue = a[leftarg];
int left = leftarg - 1;
int right = rightarg + 1;
for(;;)
{
while (a[--right] > pivotvalue);
while (a[++left] < pivotvalue);
if (left >= right) break;
T temp = a[right];
a[right] = a[left];
a[left] = temp;
}
int pivot = right;
quicksort(a, leftarg, pivot);
quicksort(a, pivot + 1, rightarg);
}
}
int main(void) {
int sortme[10];
for (int i = 0; i < 10; i++) {
sortme[i] = rand();
cout << sortme[i] << " ";
};
cout << endl;
quicksort<int>(sortme, 0, 10 - 1);
for (int i = 0; i < 10; i++) cout << sortme[i] << "
";
cout << endl;
return 0;
}
This QuickSort algorithm will sort an array of type T (whose relational and assignment
operators have been defined). The template function takes one template argument and three
function arguments:
the type of the array to be sorted, T
the name of the array to be sorted, a
the lower bound of the array, leftarg
the upper bound of the array, rightarg
L t;
list *next;
public :
list ( L t);
void add_num (list *node)
{
node->next=this;
next=NULL;
}
list *obtainnext( ) { return next;}
L getnum ( ) { return t; }
};
template <class L> list <L>::list (L y)
{
t=y;
next=0;
}
void main ( )
{
clrscr( );
list <int> obj(0);
list <int> *opt, *last;
last=&obj;
int j=0;
while (j<15)
{
opt=new list <int> (j+1);
opt->add_num (last);
last=opt;
j++;
}
opt=&obj;
j=0;
while (j<15)
{
cout<<opt->getnum( ) << " ";
opt=opt->obtainnext( );
j++;
}
}
INTRODUCTION
While writing large programs, a programmer makes many mistakes. Due to this, bugs occur
even in the released softwares. Developing an error free program is the objective and intention of
the programmer. Programmers have to take care to prevent errors. Errors can be trapped using
exception-handling features.
Few languages support exception-handling features. Without this feature, the programmers
have to find out errors himself/ herself. The errors may be logical errors or syntactic mistakes
(syntax mistakes). The logical errors remain in the program due to poor understanding of the
program. The syntax mistakes are due to lack of understanding of the programming language. C+
+ provides exception-handling procedure to reduce the errors that a programmer makes.
Object Oriented Programming and C++
compiler. When no error is found and no exception is thrown, in such a situation catch block is
disregarded and the statement after the catch block is executed.
n exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.
catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
try: A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following:
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in case your
try block raises more than one exception in different situations.
Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements. The operand
of the throw statements determines a type for the exception and can be any expression and the
type of the result of the expression determines the type of exception thrown.
Following is an example of throwing an exception when dividing by zero condition occurs:
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions:
The catch block following the try block catches any exception. You can specify what type of
exception you want to catch and this is determined by the exception declaration that appears in
parentheses following the keyword catch.
Object Oriented Programming and C++
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify that a
catch block should handle any type of exception that is thrown in a try block, you must put an
ellipsis, ..., between the parentheses enclosing the exception declaration as follows:
try
{
// protected code
}catch(...)
{
// code to handle any exception
}
The following is an example, which throws a division by zero exception and we catch it in
catch block.
#include <iostream>
using namespace std;
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Object Oriented Programming and C++
Because we are raising an exception of type const char*, so while catching this exception, we
have to use const char* in catch block. If we compile and run above code, this would produce the
following result:
Division by zero condition!
C++ Standard Exceptions
C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below:
{
// catch section-n
}
As soon as an exception is thrown, the compiler searches for appropriate by matching catch
( ) block. The matching catch ( ) block is executed and control passes to the successive statement
after the last catch ( ) block. In case no match is found, the program terminates. In multiple catch
( ) statement, if objects of many catch statements are similar to type of an exception, in such a
situation the first catch ( ) block that matches is executed.
{
try
{
if(x>0)
throw x;
else
throw 'x';
}
catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x;
}
catch(char x)
{
cout<<"Catch a character and that character is:"<<x;
}
}
void main()
{
clrscr();
cout<<"Testing multiple catches\n:";
test(10);
test(0);
getch();
}
Output:
Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x
RETHROWING EXCEPTION
It is also possible to pass again the exception received to another exception handler i.e.,
an exception is thrown from catch( ) block and this is known as rethrowing of exception. The
following statement accomplishes this:
throw;
The above throw statement is used without any argument. This statement throws the
exception caught to the next try catch statement.
The following program illustrates this.
Write a program to rethrow an exception.
# include <iostream.h>
void sub( int j, int k)
{
cout <<"inside function sub ( )\n";
try
{
if (j==0)
throw j;
else
Object Oriented Programming and C++
{
cout <<”Caught exception inside Main\n”;
}
cout << “Main end”;
return 0;
}
O/p:
Main start
Caught exception inside MyHandler
Caught exception inside Main
Main end
Thus, exception rethrown by the catch block inside MyHandler() is caught inside main();
SPECIFYING EXCEPTION
The specified exceptions are used when we want to bind the function to throw only specified
exception. Using a throw list condition can do this. The format for such exception is given
below.
Specifying Exceptions
data-type function_name (parameter list) throw (data type list)
{
Statement 1;
Statement 2; Function definition
Statement 3;
}
The data type list indicates the type of exceptions to be thrown. If we want to deny a function
from throwing exception, we can do this by declaring data type list void as per the following
statement.
throw ( ); // void or vacant list
Write a program to restrict a function to throw only specified type of exceptions.
# include <iostream>
using namespace std;
void check (int k) throw (int,double)
{
if (k==1) throw ‘k’;
else
if (k==2) throw k;
else
if (k==-2) throw 1.0;
cout <<"\n End of function check ( )";
}
void main ( )
{
try
{
cout <<"k==1\n";
check(1);
cout <<"k==2\n";
check(2);
cout <<"k==-2\n";
check(-2);
cout <<"k==3\n";
check(3);
Object Oriented Programming and C++
} catch ( char g)
{
cout <<"Caught a character exception \n";
}
catch (int j)
{
cout <<"Caught a character exception \n";
}
catch (double s)
{
cout <<"Caught a double exception \n";
}
cout <<"\n End of main ( ) ";
}
}
void operator ++ (int) // postfix notation
{ x++; }
void operator -- ( ) // prefix notation
{
--x; }
void show ( )
{
cout <<"\n x="<<x;
}
};
number :: number ( float k)
{
if (k==0)
throw number( );
else
x=k;
}
void main( )
{
try
{
number N(2.4);
cout <<"\n Before incrimination: ";
N.show ( );
cout <<"\n After incrimination: ";
N++; // postfix increment
N.show( );
cout <<"\n After decrementation:";
--N; // prefix decrement
N.show( );
number N1(0);
}
catch (number)
{
cout <<"\n invalid number";
exit(1);
}
}
{
cout <<" An uncaught exception\n";
throw two ( );
}
catch (one)
{
cout <<" Exception for one ";
}
}
Explanation: In the above program, an exception is thrown for class two using the
statementthrow two( ). The catch( ) block is defined to handle exception for class one and it
contains an argument of class one type. When an exception is thrown it does not find a match
hence the program is terminated. For termination, abort( ) function is called implicitly by the
compiler.
exit(1);
}
When errors occur, the function generating the error can 'throw' an exception. For
example, take a sample function that does division
const int DivideByZero = 10;
//....
double divide(double x, double y)
{
if(y==0)
{
throw DivideByZero;
}
return x/y;
}
The function will throw DivideByZero as an exception that can then be caught by an exception-
handling catch statement that catches exceptions of type int. The necessary construction for
catching exceptions is a try catch system. If you wish to have your program check for exceptions,
you must enclose the code that may have exceptions thrown in a try block. For example:
try
{
divide(10, 0);
}
catch(int i)
{
if(i==DivideByZero)
{
cerr<<"Divide by zero error";
}
}
he catch statement catches exceptions that are of the proper type. You can, for example, throw
objects of a class to differentiate between several different exceptions. As well, once a catch
statement is executed, the program continues to run from the end of the catch.
It is often more useful for you to create a class that stores information on exceptions as they
occur. For example, it would be more useful if you had a class to handle exceptions.
class DivideByZero
{
public:
double divisor;
DivideByZero (double x);
};
DivideByZero::DivideByZero(double x) : divisor(x)
{}
int divide(int x, int y)
{
if(y==0)
{
throw DivideByZero(x);
}
}
try
{
divide(12, 0);
}
catch (DivideByZero divZero)
Object Oriented Programming and C++
{
cerr<<"Attempted to divide "<<divZero.divisor<<" by zero";
}
The throw statement is present in the show ( ) function. The show ( )function is invoked inside
the try block. Thus, exception handling can also be defined in the above style.
When an exception not specified is thrown, it is known as unexpected exception.
In case an exception is thrown before complete execution of constructor, destructor for
that object will not be executed.
As soon as an exception is thrown, the compiler searches nearby handlers (catch blocks).
After finding a match, it will be executed.
INTRODUCTION
A string is nothing but a sequence of characters. String can contain small and capital letters,
numbers and symbols. String is an array of character type. Each element of string occupies a byte
in the memory. Every string is terminated by a null character. The last character of such a string
is null (‘\0’) character and the compiler identifies the null character during execution of the
program. In a few cases, the null character must be specified explicitly. The null character is
represented by ‘\0’, which is the last character of a string. It's ASCII and Hex values are zero.
The string is stored in the memory as follows:
char country [6] =”INDIA”;; // Declaration of an array ‘country’.
Here, text “INDIA” is assigned to array country. The text is enclosed within double quotation
mark.
string text(“C++”);
The term string generally means an ordered sequence of characters, with a first character, a
second character, and so on, and in most programming languages such strings are enclosed in
either single or double quotes. In C++ the enclosing delimiters are double quotes. In this form
the string is referred to as a string literal and we often use such string literals in output statements
when we wish to display text on the screen for the benefit of our users. For example, the usual
first C++ program displays the string literal "Hello, world!" on the screen with the following
output statement:
cout << "Hello, world!" << endl;
However, without string variables about all we can do with strings is output string literals to
the screen, so we need to expand our ability to handle string data. When we talk about strings in
C++, we must be careful because the C language, with which C++ is meant to be backward
compatible, had one way of dealing with strings, while C++ has another, and to further
complicate matters there are many non-standard implementations of C++ strings. These should
gradually disappear as compiler vendors update their products to implement the string
component of the C++ Standard Library.
1. An "ordinary" array of characters, which is just like any other array and has no special
properties that other arrays do not have.
2. A C-string, which consists of an array of characters terminated by the null character '\0',
and which therefore is different from an ordinary array of characters. There is a whole
library of functions for dealing with strings represented in this form. Its header file is
<cstring>. In some implementations this library may be automatically included when
you include other libraries such as the <iostream> library. Note that the null character
may very well not be the very last character in the C-string array, but it will be the first
character beyond the last character of the actual string data in in that array. For example
if you have a C-string storing "Hello" in a character array of size 10, then the letters of
the word "Hello" will be in positions with indices 0 to 4, there will be a null character at
index 5, and the locations with indices 6 to 9 will contain who-knows-what. In any case,
it's the null character at index 5 that makes this otherwise ordinary character array a C-
string.
3. A C++ string object, which is an instance of a "class" data type whose actual internal
representation you need not know or care about, as long as you know what you can and
can't do with variables (and constants) having this data type. There is a library of C++
string functions as well, available by including the <string> header file.
Both the C-string library functions and the C++ string library functions are available to C++
programs. But, don't forget that these are two *different* function libraries, and the functions of
the first library have a different notion of what a string is from the corresponding notion held by
the functions of the second library. There are two further complicating aspects to this situation:
first, though a function from one of the libraries may have a counterpart in the other library (i.e.,
a function in the other library designed to perform the same operation), the functions may not be
used in the same way, and may not even have the same name; second, because of backward
compatibility many functions from the C++ string library can be expected to work fine and do
the expected thing with C-style strings, but not the other way around.
The last statement above might seem to suggest we should use C++ strings and forget about
C-strings altogether, and it is certainly true that there is a wider variety of more intuitive
operations available for C++ strings. However, C-strings are more primitive, you may therefore
find them simpler to deal with (provided you remember a few simple rules, such as the fact that
the null character must always terminate such strings), and certainly if you read other, older
programs you will see lots of C-strings. So, use whichever you find more convenient, but if you
Object Oriented Programming and C++
choose C++ strings and occasionally need to mix the two for some reason, be extra careful.
Finally, there are certain situations in which C-strings must be used.
To understand strings, you will have to spend some time studying sample programs. This study
must include the usual prediction of how you expect a program to behave for given input,
followed by a compile, link and run to test your prediction, as well as subsequent modification
and testing to investigate questions that will arise along the way. In addition to experimenting
with any supplied sample programs, you should be prepared to make up your own.
In the following examples we attempt to draw the distinction between the two string
representations and their associated operations. The list is not complete, but we do indicate how
to perform many of the more useful kinds of tasks with each kind of string. The left-hand column
contains examples relevant to C-strings and the right-hand column shows analogous examples in
the context of C++ strings.
Finding the length of a C-string Finding the length of a C++ string object
-------------------------------- -----------------------------------------
strlen(str) str.length()
STRING ATTRIBUTES
The various attributes of the string such as size, length, capacity etc. can be obtained using
member functions. The size of the string indicates the total number of elements currently stored
in the string. The capacity means the total number of elements that can be stored in string. The
maximum size means the largest valid size of the string supported by the system.
size( )
The member function size( ) determines the size of the string object i.e., number of bytes
occupied by the string object. It is used in the given format.
s1.size( )
Here s1 is a string object and size( ) is a member function.
Write a program to display the size of the string object before and after initialization.
# include <iostream>
# include <string>
using namespace std;
int main( )
{
string s1;
cout <<"\nsize : "<<s1.size( );
s1="hello";
cout <<"\nNow size : "<<s1.size( );
return 0;
}
MISCELLANEOUS FUNCTIONS
assign( )
This function is used to assign a string wholly/ partly to other string object. It is used in the
following format:
s2.assign(s1)
Here s2 and s1 are two string objects. The contents of string s1 are assigned to s2.
s2.assign(s1,0,5);
In the above format, element from 0 to 5 are assigned to object s2.
Write a program to assign a sub-string from main string to another string object.
# include <iostream>
# include <string> using namespace std;
Object Oriented Programming and C++
int main( )
{
string s1("c plus plus");
string s2;
int x=0;
s2.assign(s1,0,6);
cout <<s2;
return 0;
}
OUTPUT
C plus
Explanation: In the above program, s1 and s2 are two string objects. The object s1 is initialized
with the string “c plus plus”. The object s2 invokes the assign( ) function with the integer
argument 0,6, that indicates the sub-string. The sub-string is assigned to object s2 i.e. “C plus”.
QUESTIONS
SECTION-A
1. Give any two inbuilt functions for string manipulation?
2. Define predefined streams?
3. Define file pointers?
4. List out any three error handling functions.
5. The classes derived from ios are ___________
6. What are input and output stream?
7. What are input and output stream?
8. What is a stream?
9. __________ is a sequence of bytes and serves as a source or destination for an I/O data.
10. __________ Header file provides a set of manipulation functions to manipulate output
formats.
SECTION-B
1. Write a sample program to implement the unformatted console I/O operations?
2. Write short notes on Command line argument?
3. Write a sample program to implement the command line arguments?
4. Write short notes on manipulating Strings?
5. Write a sample program to implement the formatted console I/O operations?
6. Write short notes on error handling fucntions?
7. Write short notes on file pointers?
8. Describe about unformatted console I/O operations?
9. Write short notes on predefined Streams(Standard I/O object)
10. Write short notes on streams in c++?
SECTION-C
1. Explain about string manipulation using string functions?
2. Explain about unformatted I/O operations with examples?
3. Write in detail about formatted console I/O operations using various inbilt functions?
4. Describe briefly the features of I/O systems supported by C++?
5. Explain briefly about command line argumnets?
6. Explain about predefined Streams(Standard I/O object)?
7. Explain about file pointers in C++?
8. Explain about various error handling functions in c++?
9. Explain about various Sequential Input and Output operations?
10. Explain the concepts of command line arguments using a sample program?
Object Oriented Programming and C++