Sie sind auf Seite 1von 142

EDUWING OBJECT ORIENTED PROGRAMMING WITH C++

According to the GITAM Syllabus | M.A.Srinuvasu


Object Oriented Programming with C++ Unit -1

Introduction to OOPS: Origins of C++, Object Oriented Programming, Headers &


Name Spaces, Applications of OOP, Structure of C++ Program.
C++ Basics: Keywords, Constants, Data Types, Dynamic Initialization of Variables,
Reference Variables, Operators in C++.
C++ Class Overview: Class Definition, Objects, Class Members, Access Control, Class
Scope.

The Origins of C++

C++ began as an expanded version of C. The C++ extensions were first invented by Bjarne
Stroustrup in1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new
language "C with Classes." However, in1983the name was changed to C++.

Although C was one of the most liked and widely used professional programming languages in
the world, the invention of C++ was necessitated by one major program-ming factor: increasing
complexity. Over the years, computer programs have become larger and more complex. Even
though C is an excellent programming language, it has its limits. In C, once a program exceeds
from 25,000 to100,000 lines of code, it becomes so complex that it is difficult to grasp as a
totality. The purpose of C++ is to allow this barrier to be broken. The essence of C++ is to allow
the programmer to comprehend and manage larger, more complex programs.

Most additions made by Stroustrup to C support object-oriented programming, sometimes


referred to as OOP. Stroustrup states that some of C++'s object-oriented features were inspired
by another object- oriented language called Simula67. Therefore, C++ represents the blending of
two powerful programming methods.

Since C++ was first invented, it has under gone three major revisions, with each adding to and
altering the language. The first revision was in 1985 and these condign 1990. The third occurred
during the standardization of C++. Several years ago, work began on a standard for C++. Toward
that end, a joint ANSI (American National Standards Institute) and ISO (International Standards
Organization) standardization committee was formed. The first draft of the proposed standard
was created on January 25, 1994. In that draft, the ANSI/ISO C++ committee (of which I am a
member) kept the features first defined by Stroustrup and added some new ones as well. But in
general, this initial draft reflected the state of C++ at the time.

Soon after the completion of the first draft of the C++ standard, an event occurred that caused the
language to be greatly expanded: the creation of the Standard Template Library (STL) by
Alexander Stepanov. The STL is a set of generic routines that you can use to manipulate data. It
Is both powerful and elegant, but also quite large. Subsequent to the first draft, the committee
voted to include the STL in the specification for C++. The addition of the STL expanded the

1 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

scope of C++ well beyond its original definition. While important, the inclusion of the
STL,among other things, slowed the standardization of C++.

It is fair to say that the standardization of C++ took far longer than any one had expected when it
began. In the process, many new features were added to the language and many small changes
were made. In fact, the version of C++ defined by the C++ committee is much larger and more
complex than Stroustrup's original design. However, the standard is now complete. The final
draft was passed out of committee on November 14, 1997. A standard for C++ is now a reality.

What Is Object-Oriented Programming?

Since object-oriented programming (OOP) drove the creation of C++, it is necessary to


understand its foundational principles. OOP is a powerful way to approach the job of
programming. Programming methodologies have changed dramatically since the invention of the
computer, primarily to accommodate the increasing complexity of programs. For example, when
computers were first invented, programming was done by toggling in the binary machine
instructions using the computer's front panel. As long as programs were just a few hundred
instructions long, this approach worked. As programs grew, assembly language was invented so
that a programmer could deal with larger, increasingly complex programs, using symbolic
representations of the machine instructions. As programs continued to grow, high-level
languages were introduced that gave the programmer more tools with which to handle
complexity. The first wide spread language was, of course, FORTRAN. Although FORTRAN
was a very impressive first step, it is hardly a language that encourages clear, easy-to-understand
programs.

The1960 s gave birth to structured programming. This is the method encouraged by languages
such a C and Pascal. The use of structured languages made it possible to write moderately
complex programs fairly easily. Structured languages are characterized by their support for
stand-alone subroutines, local variables, rich control constructs, and their lack of reliance upon
the GOTO. Although structured languages area powerful tool, even they reach their limit when a
project becomes too large.

Object-oriented programming took the best ideas of structured programming and combined them
with several new concepts. The result was a different way of organizing a program. In the most
general sense, a program can be organized in one of two ways: around its code (what is
happening)or a round its data ( who is being affected ). Using only structured programming
techniques, programs are typically organized around code. This approach can be thought of as
"code acting on data."For example, a program written in a structured language such as C is
defined by its functions, any of which may operate on any type of data used by the program.

2 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Object-oriented programs work the other way around. They are organized around data, with the
key principle being “data controlling access to code." In an object-oriented language, you define
the data and the routines that are permitted to act on that data. Thus, a data type defines precisely
what sort of operations can be applied to that data.

To support the principles of object-oriented programming, all OOP languages have three traits in
common: encapsulation, polymorphism, and inheritance. Let's examine each.

The New C++ Headers

As you know, when you use a library function in a program, you must include its header file.
This is done using the #include statement. For example, in C, to include the header file for the
I/O functions, you include stdio.h with a statement like this:

#include <stdio.h>

Here, stdio.h is the name of the file used by the I/O functions, and the preceding statement causes
that file to be included in your program. The key point is that this #include statement includes a
file.

When C++ was first invented and for several years after that, it used the same style of headers as
did C. That is, it used header files. In fact, Standard C++ still supports C-style headers for header
files that you create and for backward compatibility.

However, Standard C++ created a new kind of header that is used by the Standard C++ library.
The new-style headers do not specify file names. Instead, they simply specify standard identifiers
that may be mapped to files by the compiler, although they need not be. The new-style C++
headers are an abstraction that simply guarantee that the appropriate prototypes and definitions
required by the C++library have been declared.

Since the new-style headers are not file names, they do not have a .h extension. They consist
solely of the header name contained between anglebrackets.

For example, here are some of the new-style headers supported by Standard C++.

<iostream> <fstream> <vector> <string>

The new-style headers are included using the #include statement. The only difference is that the
new-style headers do not necessarily represent filenames.

3 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Because C++ includes the entire C function library, it still supports the standard C-style header
files associated with that library. That is, header files such as stdio.h or ctype.h are stil lavailable.
However, Standard C++ also defines new-style headers that you can use in place of these header
files. The C++ versions of the C standard headers simply add a "c" prefix to the file name and
drop the .h. For example, the C++ new-style header for math.h is <cmath>. The one for string.h
is <cstring>.Although it is currently permissible to include a C style header file when using C
library functions, this approach is deprecated by Standard C++ (that is, it is not recommended).
If your compiler does not support new-style headers for the C function library, then simply
substitute the old-style, C-like headers.

Since the new-style header is a recent addition to C++, you will still find many, many older
programs that don't use it. These programs employ C-style headers, in which a file name is
specified. As the old-style skeletal program shows, the traditional way to include the I/O header
is as shown here.

#include <iostream.h>

This causes the file iostream.h to be included in your program. In general, an old-style header
file will use the same name as its corresponding new-style header with an .h appended.

Name space

Namespace is a new concept introducing by the ANSI C++ Standards committee. This defines a
scope for the identifiers that are used in a program. For using the identifiers defined in the
namespace scope we must include the using directive, like
using namespace std;
Here, std is the namespace where ANSI C++ standard class libraries are defined. All ANSI C++
programs must include this directive. This will bring all the identifiers defined in std to the
current global scope. Using and namespace are the new keywords of C++.

Defining a Namespace:
We can define our own namespaces in our programs. The syntax for defining a namespace is
similar to the syntax for defining a class. The general form of name space is:
namespace namespace_name
{
// declaration of
// variables, functions, classes, etc.
}

4 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Note: there is one difference between a class defined and a namespace definition. This
namespace is concluded with a closing brace but no terminating semicolon.

Example:
namespace testspace
{
int m;
void dispalay(int)
{
cout<<m;
}
} // no semicolon here

Here , the variable m and the function display are inside the scope defined by the TestSpace
namespace. If we want to assign a value to m, we must use the scope resolution operator as a
shown below.

TestSpace :: m =100;

Note that m is qualified using the namespace.

// inner block scopes


#include <iostream>
using namespace std;

int main () {
int x = 10;
int y = 20;
{
int x; // ok, inner scope.
x = 50; // sets value to inner x
y = 50; // sets value to (outer) y
cout << "inner block:\n";
cout << "x: " << x << '\n';
cout << "y: " << y << '\n';
}
cout << "outer block:\n";
cout << "x: " << x << '\n';
cout << "y: " << y << '\n';
return 0;

5 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Out put :
x: 10
y: 50

This approach becomes cumbersome if the members of a namespace are frequently used. In such
cases, we use a using directive to simplify their access.This can be dome in two ways:

Using namespace namespace_name; // using directive


Using namespace_name::member_name; // using declaration

In the first form, all the members declared with in the specified namespace may be accessed
without qualification. In the second form, we can access only the specified member in the
program.

Example:

using namespace TestSpace;


m=100; //OK
display(200); //OK

using TestSpace : : m;
m=100; //OK
display(200); // not ok, display not visible

Example:

// namespaces
#include <iostream>
using namespace std;

namespace foo
{
int value() { return 5; }
}

namespace bar
{
const double pi = 3.1416;

6 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

double value() { return 2*pi; }


}

int main () {
cout << foo::value() << '\n';
cout << bar::value() << '\n';
cout << bar::pi << '\n';
return 0;
}

Output:
5
6.2832
3.1416

Applications of OOP:

Applications of OOP are beginning to gain importance in many areas. The most popular
application of OOP is in the area of user interface design such as windows. The other areas
include the following:
i) Real-time systems
ii) Simulation and modeling
iii) Object-oriented data bases
iv) Hypertext and hypermedia
v) AI and expert systems
vi) Neural networks and parallel programming
vii) Decision support and office automation systems
viii) CIM/CAM/CAD systems
The richness of OOP environment has enabled the software industry to improve not only the
quality of software systems but also its productivity.

7 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Structure of C++ Program:


A typical program contains 4 sections as shown below.

Include files

Class declaration
Member functions
definitions
Main function program

Structure of C++ program


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

Some of them (sections) are optional.

1) Include Files:
Like C, C++ programs also depend upon some header files.
Each header file has an extension of “.h”
For example #include<iostream.h>

2) Class Declaration or Definition:


A Class contains variables declaration, functions declaration/definition.
The class declaration must be enclosed with curly braces ({ }) and terminated by a semi
colon(;).
Syntax:
class <class name>
{
Variables declaration; // called as data members
(or) member variables
Function declaration/definition; // called as member
functions
}; // End of class

8 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

3) Class function definitions:


The class function definition can be done outside or inside the class declaration.
If function is small then define inside the class.
When the function is large then define outside the class. In this case prototype or
declaration of a function must be declared inside the class.
4) main( ) function:
Every C and C++ program execution starts from main( ) function, hence it is
compulsory.

Keywords:

The keywords implement specific C++ language features. They are explicitly reserved
identifiers and cannot be used as names for the program variables or other user-defined program
elements. For example, some authors will use keyword in the same sense that we have used
reserved word.
C++ Reserved Words
The reserved words of C++ may be conveniently placed into several groups. In the first group we
put those that were also present in the C programming language and have been carried over into
C++. There are 32 of these, and here they are:

auto const double float int short struct unsigned


break continue else for long signed switch void
case default enum goto register sizeof typedef volatile
char do extern if return static union while

There are another 30 reserved words that were not in C, are therefore new to C++, and here they
are:

asm dynamic_cast namespace reinterpret_cast try


bool explicit new static_cast typeid
catch false operator template typename
class friend private this using
const_cast inline public throw virtual
delete mutable protected true wchar_t

The following 11 C++ reserved words are not essential when the standard ASCII character set is
being used, but they have been added to provide more readable alternatives for some of the C++
operators, and also to facilitate programming with character sets that lack characters needed by
C++.

9 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

and bitand compl not_eq or_eq xor_eq


and_eq bitor not or xor

Constants:

Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.

Again, constants are treated just like regular variables except that their values cannot be modified
after their definition.

Integer literals:
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals:

212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix

Following are other examples of various types of Integer literals:

85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long

Floating-point literals:
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form. While
representing using decimal form, you must include the decimal point, the exponent, or both and

10 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

while representing using exponential form, you must include the integer part, the fractional part,
or both. The signed exponent is introduced by e or E.

Here are some examples of floating-point literals:

3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction

Boolean literals:
There are two Boolean literals and they are part of standard C++ keywords:

A value of true representing true.


A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.

Character literals:
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is
a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise,
it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').

There are certain characters in C++ when they are preceded by a backslash they will have special
meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some
of such escape sequence codes:

Escape sequence Meaning


\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits

11 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Following is the example to show few escape sequence characters:

#include <iostream>
using namespace std;

int main()
{
cout << "Hello\tWorld\n\n";
return 0;
}

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

String literals:
String literals are enclosed in double quotes. A string contains characters that are similar to
character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separate them using
whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

Defining Constants:
There are two simple ways in C++ to define constants:

Using #define preprocessor.


Using const keyword.

The #define Preprocessor:


Following is the form to use #define preprocessor to define a constant:

#define identifier value

Following example explains it in detail:

12 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

#include <iostream>
using namespace std;

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main()
{

int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}

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

50

The const Keyword:


You can use const prefix to declare constants with a specific type as follows:

Const type variable =value;

Following example explains it in detail:

#include <iostream>
using namespace std;

int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}

13 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

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

50

Note that it is a good programming practice to define constants in CAPITALS.

Data Types :
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integ er,
floating point, double floating point, boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.

Primitive Built-in Types:


C++ offer the prog rammer a rich assortment of built-in as well as user defined data types.
Following table lists

Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers:

Several of the basic types can be modified using one or more of these type modifiers:

signed
unsigned
short
long

The following table shows the variable type, how much memory it takes to store the value in
memory, and what is

maximum and minimum vaue which can be stored in such type of variables.

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647

14 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

unsigned int 4bytes 0 to 4294967295


signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int Range -32768 to 32767
long int 4bytes -2,147,483,647 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character
The sizes of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.

Following is the example, which will produce correct size of various data types on your
computer.

#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;
}

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 g et
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

15 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Size of wchar_t : 4

typedef Declarations:

You can create a new name for an existing type using typedef. Following is the simple syntax to
define a new
type using typedef:

For example, the following tells the compiler that feet is another name for int:

typedef int feet;

Now, the following declaration is perfectly leg al and creates an integ er variable called distance:

feet distance;

Enumerated Types:

An enumerated type declares an optional type name and a set of zero or more identifiers that can
be used as values of the type. Each enumerator is a constant whose type is the enumeration.

To create an enumeration requires the use of the keyword enum. The g eneral form of an
enumeration type is:

enum enum-name { list of names } var-list;

Here, the enum-name is the enumeration's type name. The list of names is comma separated.

For example, the following code defines an enumeration of colors called colors and the variable
c of type color. Finally, c is assigned the value "blue".

enum color { red, green, blue } c;


c = blue;

By default, the value of the first name is 0, the second name has the value 1, the third has the
value 2, and so on.
But you can g ive a name a specific value by adding an initializer. For example, in the following
enumeration, green will have the value 5.

enum color { red, green=5, blue };

Here, blue will have a value of 6 because each name will be one g reater than the one that
precedes it.

16 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Declaration of Variables:

All the variables must be declared before they are used in the program. Provided unlike in
C, in C++ you can declare the variables whenever there is a need for you any where in the
program even between the statements also.

Write a program to find sum and average of two numbers.


# include < iostream.h >
int main()
{
float num1, num2; //declaration of variables
cout<<”Enter two numbers:”;
cin>>num1;
cin>>num2;
float sum; //declaration
sum=num1+num2;
cout<<”Sum is:”<<sum;
float average; //declaration
average=sum/2;
cout<<”Average is:”<<average;
return 0;
}
Output:
Enter two numbers: 3.3 5.3
Sum is: 8.6
Average is: 4.3
Note: The only disadvantage of this style of declaration is that we cannot see all the variables
used in a program at a glance.

Dynamic Initialization of Variables

In C a variable must be initialized using a constant expression, C++ permits initialization of the
variables at run time using expressions at the place of declaration. This is referred to as dynamic
initialization.
Example:
int n = strlen(string); //In this n is initializing at run time
float area = 3.14 * r * r ; //In this area
Write a program in c++ to demonstrate dynamic initialization.
#include<iostram.h>
#include<conio.h>
17 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

int main( )
{
clrscr();
cout<<”Enter radius :”;
int r;
cin>> r ;
float area = 3.14 * r * r ;//variable area is declared &
assignment is carried out at run cout<<”
\n Area = “<<area; time
getch();
return 0;
}
Output:
Enter radius: 3
Area = 28.26

Reference Variables

C++ introduces a new kind of variable known as the reference variable. Reference
variable behaves similar to both, a value variable and a pointer variable i.e., a reference variable
provides an alias (alternative name) for a previously defined variable. Thus the reference variable
enjoys the simplicity of value variable and power of the pointer variable.
The general format of declaring a reference variable is:
data-type & reference-name = variable-name;

Example:
float total=100;
float & sum = total;

total is a float type variable that has already been declared. sum is the alternative name declared
to represent the variable total. Both the variable refer to the same data object in the memory.
cout<<total;
cout<<sum; // Both statements prints the value 100.
The reference variable must be initialized at the time of declaration. Initialization of reference
variable after its declaration causes compilation error. Hence, reference variables allow creating
alias of existing variables.
The following examples uses reference variable
1. int n[10];
int & x=n[10]; // is alias for n[10]
2. int x;

18 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

int *p = &x ;
int &m = *p;
3. int & n = 50;
A major application of reference variables is in passing arguments to functions.
Mainly they are three types of passing arguments to functions.
1. call by value
2. call by address
3. call by reference
Already we seen first two types in „C‟

Call by reference:

Illustrating the use of reference variable in parameter passing


#include < iostream.h >
void fun(int &x) //uses reference
{
x=x+10; //x is incremented so also m
}
int main()
{
int m=100;
cout<<”\n before call of function ”<<m;
fun(m);
//function call
cout<<”\n After call of function ”<<m;
return 0;
}

Output:
Before call of function 100
After call of function 110

In the above program the parameter „x‟ in function fun becomes an alias for the variable
„m‟ passed from main(). This type of function calls are known as call-by-reference.
Since both x and m are aliases , when the function increments x, m is also incremented. In
traditional C‟ we can accomplish this operation using pointers and dereferencing techniques.
The call-by-reference mechanism is useful in object-oriented programming because it permit
manipulation of objects by reference, and eliminates the copying of object parameters back and
forth. The reference variables not only use for built-in types, it can also use for user-defined
variables.

19 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Operators in C++

All C operators are valid in C++ also. C++ introduces some of the following new
operators along with “<<” and „>>‟ as we already used.
:: scope resolution operator
::* pointer-to-member declarator
-> pointer-to-member operator
.* pointer-to-member operator
delete memory release operator
new memory allocation operator
endl line feed operator
setw field width operator

In addition, C++ also allows us to provide new definitions to some of the build-in operators. That
is, we can give several meanings to an operator, depending upon the types of arguments used.
This process is known as operator overloading.

Scope Resolution Operator (: :)

C++ supports a mechanism to access a global variable from a function in which a local
variable is defined with the same name as a global variable. It is achieved using the scope
resolution operator. The syntax of accessing a global variable using scope resolution operator
is:
Syntax:
:: global variable-name

The global variable-name to be accessed must be preceded by the scope resolution


operator. It directs the compiler to access a global variable, instead of one defined as a local
variable. Thus, the scope resolution operator permits a program to reference an identifier in the
global scope that has been hidden by another identifier with the same name in the local scope.

Global variable access through ‘‘ : : ”


#include < iostrem.h >
int num=100; //global variable
int main()
{
int num=10; //local variable
cout<<”Local = “<<num; //accessing local variable

20 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

cout<<”Global=”<<::num; //accessing global variable


return 0;
}
Output:
Local=10
Global=100
In the above program the variable num is declared both locally and globally. The notation:: num
refers to global variable.

Member Dereferencing Operators

C++ permits us to define a class containing various types of data and functions as
members. You can access class members through pointers. In order to achieve this, C++ provides
a set of three pointer-to-members operators.

They are:
1. ::* It is used to declare a pointer to a member of a class.
2. .* It is used to access a member using object name and a pointer to that
member.
3. -->* It is used to access a member using a pointer to the object and a pointer to
that member.

Runtime Memory Management

Whenever an array is defined, a specified amount of memory is set aside at compile time,
which may not be utilized fully or may not be sufficient. If a situation arises in which the amount
of memory required is unknown at compile time, the memory allocation can be performed during
execution. Such a technique of allocating memory during runtime on demand is known as
dynamic memory allocation.

C++ provides the two special operators to perform memory management dynamically

new operator for dynamic memory allocation


delete operator for dynamic memory deallocation

These operators are simply the improved versions of the functions malloc(), calloc() and free() in
C‟ which are used for the same purpose.

21 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

An object can be created by using „new‟ operator and destroyed by using „delete‟ as and when
required. A data object created inside a block with „new‟, will remain in existence until it is
explicitly destroyed by using „delete‟. Thus, the lifetime of an object is directly under our
control.

new operator:

1) The „new‟ operator can be used to create objects of any type.


The general format is:
Pointer-varaible = new data-type;
Here, the pointer-variable is a pointer of type data-type. The „new‟ operator allocates sufficient
memory to hold a data object of type data-type (a valid data-type) and returns the address of the
object. The pointer-variable holds the address of the memory space allocated.

Example:
int *p; //declaration of a pointer variable
p=new int; //allocate two bytes of memory for p
*p=25;

2) We can also initialize memory using the new operator.


The general format for initialization is:
Pointer-variable = new data-type(value);

Example:
int *p; //declaration of a pointer variable
p=new int(25); //allocate two bytes of memory for p

3) The „new‟ operator can also be used to create memory for any data type including user-
defined data type such as arrays, structures and objects etc.
The general format for creating dynamic memory for single dimensional array is
Pointer-variable = new data-type [size];
where the size is an integer variable.

Example:
int *arr;
arr = new int[n]; //dynamically allocate memory for an
array of size „n‟
arr[0]=10; //initialize the variables

22 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

delete operator:

When a data object is no longer required, it is destroyed to release the memory space for
reuse.
The general format is:
delete pointer-variable;
The pointer-variable is the pointer that points to a data object created with „new‟.

Example:
delete p; //delete data object p of integer
To release memory for an array the general format is
delete [size] pointer variable; //where size is size of the array and it is optional

Example
delete [ ] arr ; // delete data object of an array

Manipulators

Manipulators are operators that are used to format the data display. The most commonly
used manipulators are ‘endl’ and ‘setw’.
The „endl‟ when used in output statement, causes a linefeed to be inserted. It has the same effect
of using the new line character „\n‟.

Example
cout<<”Hai“<<endl;
cout<<”Hello“<<endl;
cout<<”Bye“<<endl;
The above example produces three lines of output for each
statement.
Output:
Hai
Hello
Bye

The „setw‟ manipulator is used to display the output in the specified width. To use this
manipulator we has to include iomanip.h header file in the program.
The statement
cout<<setw(5)<<sum<<endl;
Produces the value of sum in the width of 5 characters with right-justification including the
character output.
23 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

1 0 8

Program illustrating setw and endl


#include < iostream.h >
#include < iomanip.h > // for setw
int main ( )
{
int Basic = 950, Allowance = 95, Total = 1045;
cout << setw (10) << “Basic” << setw (10) << Basic << end1
<< setw (10) << “Allowance” << setw (10) <<
Allowance << end1
<< setw (10) << “Total” << setw (10) << Total <<
end1;
return 0;
}
Output:
Basic 950
Allowance 95
Total 1045

Type Cast Operator

C++ permits explicit type conversion of variables or expressions using the type cast
operator.
The following two versions are equivalent:
(datatype_name) expression // C notation
datatypename ( expression) //C++ notation

Example:
average=sum/(float)n; // C notation
average=sum/float(n); //C++ notation

Introduction of Class:

The most important feature of C++ is the “class”. Its significance is highlighted by the
fact. A class is an extension of the idea of structure used in C. It is a new way of creating and

24 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

implementing a user-defined type (data). We shall discuss the concept of class by first reviewing
the traditional structures found in C and then the ways in which classes can be designed,
implemented and applied.

Difference between structure and Class

A structure in C is a collection of similar or dissimilar data types. C++ extends the reach
of structures by allowing the inclusion of even functions within structures.
The functions defined within a structure have a special relationship with the structures
elements presents within the structure.
There is another entity in C++ called class that too can hold data and functions.
Most of the C++ programs use structures to exclusively hold data.
Most of the C++ programs use classes to hold both data and functions.
In structures we have to give type for alias names but in case classes no need.
Objects of classes can call another without dot operator.
Structure should call its own data with a help of dot operator.

Class Definition:

A class is a way to bind the data and its associated function together. It allows the data to
be hidden, if necessary from external user. When defining a class, we are creating a new abstract
data type that can be treated like any other built is data type.

A class can be specified in two parts:-


1. Class declaration.
2. Class function definitions.
The class declaration describes the type and scope of its member.
The class function definitions describe how the class functions are implemented.
Syntax of class declaration:

class <class-name>
{
private:

25 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

variable declaration;
function declaration/definition;
public:
variable declaration;
function declaration/definition;
}; // end of the class

The functions and the variables collectively called class members.


The variables declared inside the class are known as data members and functions are member
functions.
The class members are generally grouped under two sections called private and public.
(These are the two access specifiers (or) visibility labels in C++). By default all members in
class is private i.e no external use of it. Where as in public we can access then even from out
side the class.
Note: The binding of data and functions together into a single class type variable is referred to as
encapsulation.
Let’s have an example about class:-
A typical class declaration:-
class item
{
int number; // variable declaration
float cost; // private by default
public:
void getdata (int a, float b); // functions declaration
void putdata (void); // using prototype
}; // ends with semicolon

Creating Objects:

Once a class has been declared, we can create variable of that type by class name. The class
variables of class are called as objects.

26 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

The declaration of an object is similar to that of a variable of any basic type. And the necessary
memory space is allocated to an object at this stage.
Syntax:
classname variablename;
This variablename is nothing but object of type classname.
Example:
item x;
We may also declare more than one object in one statement.
item x , y , z ;
Objects can also be created when a class is defined by placing their names immediately after the
closing brace, as we do in case of structures.
Example:
class item
{
---------------------
---------------------
---------------------
}x,y,z; // here x , y , z are objects

Class Members:

A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. It operates on any object of the class of which it is a member, and has
access to all the members of a class for that object.
Let us take previously defined class to access the members of the class using a member function instead
of directly accessing them:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};

27 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Member functions can be defined within the class definition or separately using scope resolution
operator,::. Defining a member function within the class definition declares the function inline,
even if you do not use the inline specifier. So either you can define Volume() function as below:

class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

double getVolume(void)
{
return length * breadth * height;
}
};

If you like you can define same function outside the class using scope resolution operator, :: as
follows:

double Box::getVolume(void)
{
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before :: operator. A
member function will be called using a dot operator (.) on a object where it will manipulate data
related to that object only as follows:

Box myBox; // Create an object

myBox.getVolume(); // Call member function for the object

Example:

#include <iostream>

using namespace std;

class Box
{

28 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void)
{
return length * breadth * height;
}

void Box::setLength( double len )


{
length = len;
}

void Box::setBreadth( double bre )


{
breadth = bre;
}

void Box::setHeight( double hei )


{
height = hei;
}

// Main function for the program


int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
29 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560

Access Control:

Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced namely,
Public
Private
Protected

These access specifiers are used to set boundaries for availability of members of class be it data
member or member functions.
Access specifiers in the program are followed by a colon. You can use one, two or all 3
specifiers in the same class to set different boundaries for different class members. They change
the boundary for all the declaration that follow them.

Public:

30 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Public means all the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. Hence
there are chances that they might change them. So the key members must not be declared public

class publicAccess
{
public: // public access specifier
int x; // data member declaration
void display(); // member function declaration
}

Private:

Private keyword, means that no one can access the class members declared private outside that
class. If someone tries to access the private member, they will get a compiler time error. By
default class variables and member functions are private.

class privateAccess
{
private: // privateaccess specifier
int x; // data member declaration
void display(); // member function declaration
}

Protected:

Protected id the last access specifier, and it is similar to private, it makes class members
inaccessible outside the class. But they can be accessed by any subclass of that class.(if class A is
inherited by class B, then class B is subclass of class A)

class protectedAccess
{
protected: // protectedaccess specifier
int x; // data member declaration
void display(); // member function declaration
}

31 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Class Scope
A name declared within a member function hides a declaration of the same name whose
scope extends to or past the end of the member function's class.

When the scope of a declaration extends to or past the end of a class definition, the regions
defined by the member definitions of that class are included in the scope of the class. Members
defined lexically outside of the class are also in this scope. In addition, the scope of the
declaration includes any portion of the declarator following the identifier in the member
definitions.

The name of a class member has class scope and can only be used in the following cases:

In a member function of that class


In a member function of a class derived from that class
After the . (dot) operator applied to an instance of that class
After the . (dot) operator applied to an instance of a class derived from that class, as long
as the derived class does not hide the name
After the -> (arrow) operator applied to a pointer to an instance of that class
After the -> (arrow) operator applied to a pointer to an instance of a class derived from
that class, as long as the derived class does not hide the name
After the :: (scope resolution) operator applied to the name of a class
After the :: (scope resolution) operator applied to a class derived from that class

32 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1

Questions :

33 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ UNIT-II

Parameter passing methods, static class members, this pointer, Arrays of Objects,
Objects as Function Arguments, Default Arguments, Constant Arguments, Inline
functions, Function Overloading, Friend Functions, Dynamic memory allocation and
deallocation (new and delete)

Parameter Passing Methods

Parameter passing mechanism for communication of data and information between the calling
function (caller) and called function (calle). It can be achieved either by passing the value or
address of the variable. C++ supports the following 3 types of parameter passing:
a) Pass by value
b) Pass by address
c) Pass by reference.
The parameters used to transfer data to a function are known as input parameters and those used
to transfer the result to the caller are known as output parameters. The parameters used to
transfer data in the directions are called input/output parameters. Parameters can be classified as
formal and actual parameters. Formal parameters are those specified in the function declaration
and definition. Actual parameters are those specified in the function call. The following
conditions must be satisfied for function call.
a) The number of arguments in the function call and the function declaration must be
same.
b) The data type of each of the arguments in the function call should be the same as the
corresponding parameter in the function declaration statement. However the name of
the arguments in the function call and parameter in function definition can be
different.
VALUE:
void swap(int x, int y)
{
int t;
t=x;
x=y;

1 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

y=x;
}
------------------
------------------
{
swap(a,b)
}

POINTER:

void swap(int *x, int *y)


{
int t;
t=*x;
*x=*y;
*y=t;
}
---
---
{
swap(*a, &b)
}

ADDRESS:

void swap(int &x , int &y)


{
int t;
t=x;
x=y;
y=t;
}
---
---
{
swap(a,b);
}

2 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

Static Class Members

A data member of a class can be qualified as static. The properties of a static member
variable are similar to that of a C static member variable has certain special characteristics. These
are:-

It is initialized to zero when the first object of its class is created. No other initialization is
permitted.
Only one copy of that member is created for the entire class and is shared by all the
objects of that class.
It is visible only within the class, built lifetime is the entire program.
The class and scope of the static member variable is defined outside the class declaration.
That is
General form:

return_type class_name :: static_variable;

Program: illustrates the use of static data members.

#include<iostream.h>
#include<conio.h>
class number
{
private:
static int c;
int n;
public:
void normal( )
{
n=0;
}
void count( )
{
c ++;
n++;
3 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

cout<<endl<<”value of c=”<<c<<”address of
c=”<<(unsigned)&c;
cout<<endl<<”value of n=”<<n<<”address of
n=”<<(unsigned)&n;
}
}; // end of class
int number :: c;//we can also initialize the value like int number ::
c=(0 or anynumber);
int main( ) //by default zero.
{
number A , B , C ;
clrscr();
A.normal();
B.normal();
C.normal();
A.count();
B.count();
C.count();
getch();
return 0;
}

Output:
value of c= 1 address of c= 1111

value of n= 0 address of n= 2222 // for object A result

value of c= 2 address of c= 1111

value of n= 0 address of n= 3333 //for object B result

value of c= 3 address of c= 1111

4 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

value of n= 0 address of n= 4444 //for object C result

Static Member function

Like static member variable, we can also have static member function.

Characteristics of member functions

A Static function can have access to only other static members declared in the
same class.
A static member function can be called using the class name.
Class-name:: function-name;

Let‟s have an example illustrating the above topics.

#include <iostream.h>
class test
{
int code;
static int count; // static member variable

public:
void setcode( )
{
code = ++count; // in this static data member is
incrementing i.e count
}
void showcode( )
{
cout<<”object number :”<< code <<endl ;
}
static void showcount ( ) // static member function
{
cout<<”count:”<<count<<endl ;//in this only static members
can access
}

5 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

}; //end of the class


int test : : count; // definition of static data member

int main ( )
{
test t1 , t2;
t1.setcode ( );
t2.setcode ( );
test : : showcount ( ); // accessing static function
test t3;
t3.setcode( );
test : : showcount( );
t1.showcode ( );
t2.showcode ( );
t3.showcode ( );
return (0);
} // end of int main
Output:
count : 2
count : 3
object number : 1
object number : 2
object number : 3

This Pointer

C++ contains a special pointer called „this„. The „this‟ pointer is automatically passed into any
member function when it is called and it is a pointer to the object that generates the call. Thus
any member function can find out the address of the object of which it is a member. Only the
member functions have this privilege of passing a „this‟ pointer. A friend function does not have
a „this‟ pointer. The „this‟ pointer has several uses. The statement
return *this;
inside a member function will return the object that invoked the function. The „this‟ pointer can
be treated like any other pointer to an object, and can thus be used to access the data in the object
it points to. Further it is very useful in operator overloading.
6 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

Arrays of Objects

We know that an array can be of any data type including struct. Similarly, we can also have
arrays of variables that are of the type class. Such variables are called arrays of objects.
Consider the following class
class employee
{
char name[30];
float age;
public:
void getdata();
void putdata();
};
The identifier employee is a user-defined data type(class) and can be used to create objects that
related to different categories of the employees.
Example:
employee manager[ 3 ]; // array of manager object
employee foreman[ 10 ]; // array of foreman object
employee worker[ 30 ]; // array of worker object

The array manager contains three objects (managers), namely, manager[0], manager[1]
and manager[2] of type employee class. Similarly for foreman‟s and workers.
We can access the members of class through arrays of object with dot operator.
For example:
manager [ i ] . getdata( );
will display the data of the ith element of array manager.
Program:
#include<iostream.h>
#include<conio.h>

class Student
{
char name[ 30 ];

7 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

int rno;
float sgpa;
public:
void getdata( );
void putdata( );
};
void Student : : getdata( )
{
cout<<”Enter name:”;
cin>>name;
cout<<”Enter roll no:”;
cin>>rno;
cout<<”Enter SGPA:”;
cin>>sgpa;
}
void Student : : putdata ( )
{
cout<<”Name:”<<name<<endl;
cout<<”Roll No:”<<rno<<endl;
cout<<”SGPA:”<<sgpa;
}
int main( )
{
clrscr( );
Student secc4[ 66 ] ;
cout<<”Reading the details of c4-section students:”<<endl;
for( int i=0 ; i<66 ; i++ )
{
secc4[ i ] . getdata( ) ;
}
cout<<”Displaying the details of c4-section students:”<<endl;
for( int i=0 ;i<66 ; i++ )
{
secc4[ i ] . putdata( );
}
getch( );
return 0;
}

Objects as Function Arguments

Like any other type, an object may be used as function argument. This can be in two ways.

8 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

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


Only the address of the object is transferred to the function.
The first method is called pass by value and the other is called pass by reference. When an
address of the object that any changes made to the object directly on the actual object used in the
call. This means pass by reference method is more efficient since it requires to pass only the
address of object and not the entire object.

Example:

#inlude<iostream.h>

class Time

int hours;

int minutes;

public:

void gettime (int h, int m)

hours = h;

minutes = m;

void puttime ( )

cout<<hours<<”hours and”;

cout<<minutes<<”minutes”<<endl;

void sum ( Time , Time ); //declaration with object as


arguments

};

void Time :: sum ( Time t1, Time t2) // t1,t2 are objects

9 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

minutes = t1.minutes + t2.minutes;

hours = minutes/60;

minutes = minutes %60;

hours = hours + t1.hours + t2.hours;

int main( )

Time t 1 , t2 , t3 ; // Three objects

t1.gettime(19, 45);

t2.gettime(3,30);

t3.sum( t1 , t2 );

cout <<”T1=”;

t1.puttime( ); //display t1

cout <<”T2=”;

t2.puttime( ); //display t2

cout <<”T3=”;

t3.puttime( ); //display t3

return 0 ;

} // end of the main

Returning Objects

A function can not only receive objects as arguments but also can return then.
Example:

#inlcude<iostream.h> // x + i y form

class complex
10 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

float x ; // real part

float y ; // imaginary part

public:

void input ( float real , float img )

x = real ;

y = img ;

complex sum ( complex , complex ); // function


returning object

void show ( complex );

};

complex complex : : sum (complex c1 , complex c2)

complex c3; // objects c3 is created

c3.x = c1.x+c2.x; // x = real, y = ing

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

return ( c3 ); // returns objects c3

void complex : : show ( complex c)

cout<< c.x << “ + i “ << c.y <<endl;

int main( )

complex A , B , C ; // Three objects

11 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

A.input( 3.1 , 5.65 );

B.input( 2.75 , 1.2 );

C = C.sum( A , B ); // function calling and it is


returning object

//and that object assigned to C object.

cout<<”A=”;

A.show( A );

cout<<”B=”;

B.show( B );

cout<<”C=”;

C.show( C );

return 0;

Default Arguments

C++ has the ability to pass its own default arguments within a functional call, if not represented.
The default arguments are used if the calling function does not supply the argument values when
function is called.
The missing arguments should always be trailing arguments(right to left).
Default arguments are signed only in functions prototype(declaration) and should not be repeated
in the function definition.
Whenever the function is called, if the function defines default arguments then it will goes to
prototype and then jumps to function definition.
Default values specified when the function is declared, and must be initialize the variables from
right to left.
We cannot provide initialization of variables in the middle of the argument list.

12 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

Some examples of function declaration with default values are:

int mul( int i , int j=5 , int k=10 ); //legal

int mul( int i=5 , int j ); //illegal

int mul( int i=3, int j, int k=6 ); //illegal

int mul( int i=2,int j=7, int k=10 ); //legal

Program: Write a program to define function sum( ) with default arguments.

# include<iostream.h>

int main( )

int sum( int a, int b=10, int c=15, int d=20); // function
declration

int a=2;

int b=3;

int c=4;

int d=5;

cout<<”Sum=”<<sum( a, b, c, d );

cout<<”\nSum=”<<sum( a, b, c );

cout<<”\nSum=”<<sum( a, b );

cout<<”\nSum=”<<sum( a );

cout<<”\nSum=”<<sum( a, c, d );

return 0;

int sum( int i, int j, int k, int l )

13 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

return ( i+j+k+l );

Output:

Sum=14

Sum=29

Sum=40

Sum=47

Sum=32

Constant Arguments

The constant variable can be declared using const keyword. It makes variable value stable. The
constant variable should be initialized while declaring.

Syntax:

a) const <variablename> = value;

b) <functionname> ( const <type>*<variablename> );

Example:

int const x; //invalid

int const x=5; //valid

The const modifier assigns an initial value to a variable that cannot be changed later by program.

In C++, an argument to a function can be declared as const as shown below.

int function1( const char*p );

14 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

int function2( const string &s);

The const tells the compiler that the function should not modify the argument. The compiler will
generate an error when this condition is violated. This type of declaration is significant only
when we pass arguments by reference or pointers.

Inline Functions

C++ proposes a new feature called inline function. It is a function that is expanded in line when
it is invoked.

That is, the compiler replaces the function call with the corresponding function
code(something similar to macros expansion).

It is easy to make a function inline, prefix the keyword inline to the function definition.
All inline functions must be defined before they are called.

The inline functions are defined as follows:

inline function_header

function body

Some of the situations where inline expansion may not work are:

If functions contains a loop, a switch, or a goto.


For functions not returning values, if a return statement exists.
If functions contain static variables.
If functions are recursive
Note: Inline expansion makes a program run faster because the overhead of a function

call and return is eliminated.

15 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

Program: illustrates the use of inline function.

#include<iostream.h>

inline int mul( int x, int y)

return ( x * y);

inline float div(float p, float q)

return ( p / q);

int main( )

int a=4, b=2;

float c=8.45,d=5.35;

cout<<”The mul result:”<<mul( a , b )<<endl;

cout<<”The div result:”<<div( c , d )<<endl;

return 0;

Output:

The mul result: 8

The div result: 1.5794

Function Overloading

It is possible in C++ to use the same function name for multiple functions.
Defining multiple functions with same name is known as function overloading or
function polymorphism. Polymorphism means a function having many forms.

16 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

The overloaded functions must be differing in no of arguments (or) types of arguments


(or) order of argument list.
Principles of function overloading:

If two functions have the similar type in its number of arguments with data types, but the
return types are different then those functions cannot be overloaded.

Example:

int sum( int , int );

float sum( int , int );

functions cannot be overloaded.

The functions return type may be similar (or) void, but it must be different in number of
arguments or arguments data types.
Example1:

sum( int , int );

sum( float , float);

In the above example number of arguments is same in both the functions, but data types
are different. Hence the above functions can be overloaded.

Example2:

sum( int , int );

sum( int , int ,int );

In the above example data types of arguments are same in both the functions, but number
of arguments is different. Hence the above functions can be overloaded.

Program: illustrate the function overloading. (Without Class).

#include<iostream.h>

17 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

#include<conio.h>

int add( int x , int y) //two integer arguments

return x+y ;

float add( int x , float y) //one int and float arguments

return x+y;

float add( float x , int y) //one float and int arguments

return x+y;

float add( float x , float y) //two float arguments

return x+y;

int main( )

int a , b;

float c , d;

cout<<”\n Enter any two integers:”;

18 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

cin>> a >> b;

cout<<”\n Enter any two floats:”;

cin>> c >> d;

cout<<”\n Calling the add (int,int):=”;

cout<< add ( a , b );

cout<<”\n Calling the add (int,float):=”;

cout<< add( a , c );

cout<<”\n Calling the add (float,int):=”<< add( c , b );

cout<<”\n Calling the add (float,float):=”<< add( c , d );

return 0;

Output:

Enter any two integers: 2 5

Enter any two floats: 3.5 7.4

Calling the add (int,int):= 7

Calling the add (int,float):= 5.5

Calling the add (float,int):= 8.5

Calling the add (float,float):= 10.9

Program: illustrate the function overloading. (With Class).

#include<iostream.h>

#include<conio.h>

19 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

class funover

int i ;

float f;

public:

int sqr( int x )

i = x*x;

return i ;

float sqr( float y )

f = y*y;

return f ;

}; //end of class

int main( )

clrscr( );

funover F ; // object created

int a=5;

float b=2.5;

20 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

cout<<”Square of integer no:”<< F.sqr( a ) ;

cout<<”\n Square of float no:”<< F.sqr( b );

return 0;

} //end of main()

Output:

Square of integer no: 25

Square of float no: 6.25

Friend Functions

Private member functions can‟t be accessed from outside the class, i.e. a non number
function can‟t have an access to the private data of a class.
In real world programming there could be a situation where we would like two classes to
share a particular function.
In C++ common function can be made friendly with the both classes, which allows the
function to have access to private data of these classes.
These types of functions need not be members of any of these classes
To make an outside function a “friendly” to a class

Syntax:

class <classname>

member;

public:

members;

friend void <function name > ( argument );

21 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

};

Characteristics of Friend Function

The function declaration should be preceded by the keyword friend.


Function definition doesn‟t use either the keyword friend (or) scope resolution (::)
operation
A function can declared as friend in any no.of classes. Though it is non member function
it has all access rights of private members of classes.
Not in the scope of class to which it‟s declared as friend.
Since it is not in the scope of the class, it can‟t be called using the object of that class.
It can be invoked like normal function without the help of any object.
Can‟t access the members directly, it has to use an object name and dot operator .
Can be declared either in public (or) private of class
Have objects as arguments.
Called by reference
In this a pointer to the address of object is passed and the called function directly works
on actual object used in the call
The above method can be used to alter the values of private members of class

Example-1: Program to illustrate Friend Functions:

#include<iostream.h>
class A
{
int x;
public:
void accept( )
{
cout<<”Enter x:”;
cin>>x;
}
friend int add_objects(A ,A ); //decleration of
friend function

22 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

};
int add_objects(Aa1,Aa2) //definition of friend function
{
return (a1.x+a2.x);
}
void main
{
A a1, a2;
A1.accept ();
A2.accept ();
cout<<”Sum of both values”<<add_objects(a1,a2);
}
Output:
Enter x : 10
Enter x : 25
Sum of both values : 35
Example-2: Develop a program to calculate the sum of integers of two classes using friend sum
functions.

#include<iostream.h>

class B; // forward declaration


class A
{
int x;
public:
void accept()
{
cout<< “Enter X :”;
cin>>x;
}
friend int sumclasses(A , B); //friend function
declaration
}; //end of class
class B

23 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

{
int y;
public:
void accept( )
{
cout<<”Enter Y :”;
cin>>y;
}
friend int sumclasses(A , B);// friend function in
two classes
};

int sumclasses(A a, B b) //friend function definition


{
return ( a.x + b.y );
}
int main( )
{
A a;
B b;
a.accept( );
b.accept( );
cout<<”Sum of both classes:”<<sumclasses (a, b);
//friend function calling
return (0);
}
Output:
Enter X : 4
Enter Y : 5
Sum of both classes : 9

Friend Class

24 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

When all the functions need to access another class in such a situation we can declare an
entire class as friend class.
The friend is not transferable (or) inheritable one to another.
Declaring class A to be a friend of class B doesn’t mean that class B is also friend to class A.
i.e. friendship is not exchangeable.
Example:

#include<iostream.h>

class A
{
int x;
friend class B; // Be ready to friendship with B & it
is for Class A
public: void accept( )
{
cout<<Enter X :”;
cin>>x;
}
};
class B
{
int y;
public:
void accept( )
{
cout << “Enter Y :”;
cin>>y;
}
void show(A a ) //It is getting data from class A
{
cout<<”Value of no. of class A “<<a.x;
cout<<”Value of no. of class B”<<y;
cout<<”Sum of two no’s”<<a.x+y;
}
};
int main( )
{
A a;
a.accept ();
B b;
b.accept( );

25 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

b.show(a); //Here “show” is in Class B but we are calling with


Object of A
return 0;
}

Dynamic Memory Allocation and Deallocation (new and Delete)

A good understanding of how dynamic memory really works in C++ is essential to becoming a
good C++ prog rammer. Memory in your C++ prog ram is divided into two parts:

The stack: All variables declared inside the function will take up memory from the stack.

The heap: T his is unused memory of the prog ram and can be used to allocate the memory
dynamically when prog ram runs.
Many times, you are not aware in advance how much memory you will need to store particular
information in a defined variable and the size of required memory can be determined at run time.
You can allocate memory at run time within the heap for the variable of a g iven type using a
special operator in C++ which returns the address of the space allocated. T his operator is called
new operator.
If you are not in need of dynamically allocated memory anymore, you can use delete operator,
which deallocates memory previously allocated by new operator.

The new and delete operators:

T here is following g eneric 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

T he 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;

26 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

if( !(pvalue = new double ))


{
cout << "Error: out of memory." <<endl;
exit(1);
}

T he malloc () function from C, still exists in C++, but it is recommended to avoid using malloc()
function. T he main advantag e 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
*pvalue = 29494.99; // Store value at allocated address
cout << "Value of pvalue : " << *pvalue << endl;
delete pvalue; // free up the memory.
return 0;
}
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

T o remove the array that we have just created the statement would look like this:

delete [] pvalue; // Delete array pointed to by pvalue


27 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

Following the similar g eneric 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 g oing 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!
28 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II

Constructor called!

Constructor called!

Destructor called!

Destructor called!

Destructor called!

Destructor called!

29 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

UNIT-III
Constructors, Parameterized Constructors, Multiple Constructors in a Class, Constructors
with Default Arguments, Dynamic initialization of Objects, Copy Constructors, Dynamic
Constructors, Destructors.
Introduction to inheritance, Defining Derived Classes, Single Inheritance, Multiple
Inheritance, Multi-Level Inheritance, Hierarchical Inheritance, Hybrid Inheritance, Virtual
Base Classes, Abstract Classes, Constructors in Derived Classes.

Constructors

C++ provides two special member functions called constructor and destructor, for automatic
initialization and deletion of objects. When the object is created, the constructor enables the
object to initialize the data items in it. On the other hand the destructor destroys the object, when
it is no longer in use.

In the case of objects, variables with user-defined data types, these tasks, such as automatic
initialization and destruction are done by special member functions called constructors and
destructors. At the time of creation of an object, the constructor in the object automatically
initializes the data members in the object. Destructors are used to destroy those objects created
by the constructors. Destructors removes from the memory the work shop occupies by the object,
which is no longer required.

Parameterized Constructors

A constructor that can be take arguments is called a parameterized constructor with arguments.
The variables in the object are initialized by the parameter values passed through the constructor.
The actual parameters present in the invocation of the constructor are assigned to the formal
parameters of the constructor definition. The values passed are thus assigned to the respective
data member in the object.
calss_name(arguments_list) { }

eg: complex (int x, int y)


{
real=x;
imaginary=y;
}

Program:

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

1 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

#include<string.h>
usage namespace std;

class student
{
private:
char name[15];
char rollno[9];
public:
student(char n[15],cahr r[9])
{//parameterized constructor declared and defined
strcpy(name,n);
strcpy(rollno,r);
}
void putdata();

};
void student::putfdata()
{
cout<<"\n Name: "<<name;
cout<<"\n Rollno: "<<rollno;
}
void main()
{
char name[15],rollno[9];
cout<<"Enter your name :";
cin>> name;
cout <<"Enter your rollno:";
cin>> rollno;
student s(name,rollno); //obj creation and constructor
invocation
s.putdata();
getch();

Note: constructor can be invoked either by an implicit call or by an explicit call.


student s = student(name. rollno);
is the explicit call for invoking the constructor.
student s(name, rollno);

2 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Is the implicit call for invoking the constructor.

Multiple Constructors in a Class

Just like function overloading, constructors can be overloading. Since C++ permits function
overloading and constructors are special functions in a class, they also overloaded. This implies
that within a class we can have more than one constructor. These overloaded constructors are
distinguished either by the number of arguments or by the data types of the arguments.

example: number(); //no arguments


number(int); //one arguments
number(int, int); //two arguments
number(int, float); //differed by the datatype of arguments

program:

#include<iostream>
usage namespace std;

class student
{
char *name;
char rollno;
public:
student() // constructor with no arguments
{
cout<<"Enter the Name and Rollno:";
cin>>name;
cin>>rollno;
}
student(char *s, char r)
{
strcpy(name s); //overloaded constructor
rollno=r;
}
student(student &p) //overloaded Constructor
{
strcpy(name,p.name);
rollno=p.rollno;
}
void didplay();

3 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

};
void student::display()
{
cout<<"Name="<<name;
cout<<"Rollno="<<rollno;
}
void main()
{
student s;
s.display();
student s1("ABC","A101");
s1.display();
student s2("xyz","A102");
s2.display();
}

Result :

Enter the Name and Rollno: pqr A103


Name = pqr
Rollno =A103

Name = ABC
Rollno =A101

Name = xyz
Rollno =A102

Constructors with Default Arguments

Like other functions in C++, constructors can also be defined with default arguments. If an
arguments are initialized at the time of constructor declaration/definition, then that type of
constructors are called default argument constructor.
The initialization of arguments at the time of constructor declaration must be in trailing
order. And the missing arguments must be the trailing ones.

Program: Illustrate the default argument constructor


#include<iostream>
usage namespace std;

class power
4 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

{
int num;
int pwr;
int ans;
public:
power(int n = 3 , int p = 2 );
void show( )
{
cout<< num <<”power”<< pwr
<<”is:”<< ans ;
}
};
power :: power( int n,int p)
{
num = n;
pwr = p;
ans = pow( n , p ) // math pow function
}
int main( )
{
clrscr( );
power p1, p2(5);
p1.show( );
p2.show( );
return 0;
}

Result:
3 power 2 is 9

5 power 2 is 25

Dynamic initialization of Objects

Class object can be initialized dynamic too. The initial value of an object may be provided
during run time. One advantage of dynamic initialization is that we can provide various
initialization formats, using overloaded constructors. This provides the flexibility of using
different format of data at run time depending upon the situation.

5 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Copy Constructors

The copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. The copy constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one. If the class has
pointer variables and has some dynamic memory allocations, then it is a must to have a copy
constructor.

The syntax for user defined Copy constructor is


class_name(class_name & obj)
{
// body of constructor
}

program:

#include <iostream>

using namespace std;

class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor

private:
int *ptr;
};

// Member functions definitions including constructor


Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;

6 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

ptr = new int;


*ptr = len;
}

Line::Line(const Line &obj)


{
cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}

Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}

void display(Line obj)


{
cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program


int main( )
{
Line line(10);

display(line);

return 0;
}

After Execution Result

Normal constructor allocating ptr


Copy constructor allocating ptr.
Length of line : 10
7 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Freeing memory!
Freeing memory!

Dynamic Constructors

The constructor can also be used to allocate memory while creating objects. This will enable the
system to allocate the right amount of memory for each object. Allocation of memory to objects
at the time of their construction is known as dynamic construction of objects. The memory is
allocated with the help of the new operator.

Program: illustrate the working of dynamic constructors:

#include<iostream.h>
class Sample
{
char *name;
int length;
public:
Sample( )
{
length = 0;
name = new char[ length + 1];
}

Sample ( char *s )
{
length = strlen(s);
name = new char[ length + 1 ];
strcpy( name , s );
}
void display( )
{
cout<<name<<endl;
}
};
int main( )
{
char *first = “ C++ “;

8 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Sample S1(first), S2(“ABC”), S3(“XYZ”);


S1.display( );
S2.display( );
S3.display( );
return 0;
}

RESULT :
C++
ABC
XYZ

Destructors

Destructors are used to distroy the objects that have been created. when an object goes out of
scope, destructor automatically removes from the memory the workspace occupied by the object.
Like constructor, destructor is also a member function, which has the same name as its
class_name, but preceded by a tilde sign (~). futuer it has no return type.for example the
destrucvtor for the class code is defined as follows.

syntax: ~code( )
{ body destructor }

The following are the characteristics of destructors

Destructors is used to destroy the work space of the object created


Destructors neither takes any arguments nor it returns any value
Destructors cannot be overloaded
It should have public access in the class declaration
It will be invoked implicitly by the compiler whenever an instances of the class to which
it belongs goes out of existence
The primary usage of a destructor is to clean up and release memory space for future use
Whenever 'new' operator is used in the constructors to allocate memory, we should use
'delete' to free that memory space.

Program:

#include <iostream>

using namespace std;

9 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

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

private:
double length;
};

// Member functions definitions including constructor


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

void Line::setLength( double len )


{
length = len;
}

double Line::getLength( void )


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

// set line length


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

return 0;

Result:

10 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Object is being created


Length of line : 6

Object is being deleted

Introduction to inheritance

In order to maintain and reuse the class objects easily, it is required to relate different classes.
Two or more classes can be related under a given relationship. Such a relationship between
classes can be referred to as “has a” relationship i.e. class A “has a” relationship with class B.

Inheritance is one of the most powerful features of OOP. Reusability is the basic objective
behind inheritance. When a class needs some of the features of a previous class we can easily
inherit those features without rewriting them, thus avoiding code repetition. C++ strongly
supports the reusability concept in several ways. A class may be derived from one or more
classes or from one or more levels, if the derived class is obtained using one base class it is
called single inheritance. if the derived class is obtained using more than one base class it is
called multiple inheritance. On the other hand if the same base class is used to derive more
number of derived classes it is referred to as hierarchical inheritance. If a class is derived from
another derived class, then the process is called multilevel inheritance. In case different types are
combined, then it is called hybrid inheritance. The main advantages of inheritance are

Reusability of the code


Increase the reliability of the code
Enhance the capability of the base class

11 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Defining Derived Classes

A derived class can be defined by specifying its relationship with the base class in addition to its
own details. The general form of defining a derived class is:
Class derived –class-name: visibility-mode base-class-name
{
……….
……….// members of derived class
……….
};

The colon indicates that the derived-class-name is derived from the base –class-name. The
visibility-mode is optional and if present, may be either private or public. The default visibility-
mode is private. Visibility mode specifies whether the features of the base class are privately
derived or publicly derived.

C++ provides a no. of ways to establish access to class members. One such access control
mechanism is the derived class are declared. A derived class can be declared with one of
the access control specifiers private, public or protected and thus there are 3 types of
derivations. The access specifier determines how the derived class inherits the elements of
the base class.
Public Derivation:
When the access specifier for the inherited base class is public, all public member of the
base class become public member of the derived class. All protected members of the base
class become protected members of the derived class. All private members of the base
class remain private to it and are inaccessible by the derived class.

Eg:
class base A
{
private:
public:
int a; //member data
};
class derivedB: public basea
{
private:
public:
};
void main()
{
derivedB test;
cin>>test.A;
12 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

cout<<test.A;
}
Private Derivation:
If the access specifier is private, all public members of the base class becomes private
member of the derived class and they are accessible by the member function of the derived
class. All protected members of the base class also becomes private members of the
derived class. All private members of the base class are remain to it and are inaccessible by
the derived class.
Eg:
class baseA
{
private:
public:
int a;
};
class derived: private baseA
{
private:
public:
void read()
{
cin>>a;
}
void display()
{
cout<<a;
}
};
void main()
{
derived sample;
sample.read();
sample.disp();
}
Protected Derivation:
A base class can also be inherited with the access specifier protected by a derived class
then the public and protected members of the base class become protected member of the
derived class. All private members of the base class remains private to it and are
inaccessible by the derived class.

Eg:

13 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

class baseA
{
private:
protected:
int a;
public:
};
class derived: public baseA
{
private:
public:
void read()
{
cin>>a;
}
void disp()
{
cout<<a;
}
};
void main()
{
derivedB sample;
sample.read();
sample.disp();
}

DERIVED CLASS VISIBILITY


BASE CLASS PUBLIC PRIVATE PROTECTED
VISIBILITY DERIVATION DERIVATION DERIVATION
PUBLIC Public Private Protected
PRIVATE Not inherited Not inherited Not inherited
PROTECTED Protected Private Protected

Single Inheritance

This type of inheritance is also known as simple inheritance, as there is only one base class and
only one derived class, the simple form of inheritance.

14 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

B
class A is the base class and class B the derived class.Class B inherits all the public and protected
members from class A. If the derivation is public, the protected or public member of Class A are
respectively protected or public in B. If the derivation is private all the protected and public
members of class A are private in B, whereas if the derivation is protected, all the protected and
public members of class A are protected in B.

Illustrates single inheritance using public derivation

#include<iostream>
using namespace std;
class stud
{
private:
char name[20];
char roll[8];
protected:
int age;
public:
void getstudent()
{
cout<<"Name:";
cin>>name;
cout<<"Roll:";
cin>>roll;
cout<<"Age";
cin>>age;
}
void showstudent()
{
cout<<endl<<"Name:"<<name<<endl<<"Roll:"<<roll<<endl;
cout<<"Age:"<<age<<endl;
}
};
class student:public stud
{
private:
15 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

int rank;
public:
void inputdata()
{
cout<<"Rank:";
cin>>rank;
}
void modifydata()
{
char bool;
cout<<endl<<"Do you want to modify?(y/N):";
cin>>bool;
if(bool=='Y')
{
cout<<"Age:";
cin>>age;
cout<<"Rank:";
cin>>rank;
}
}
void outputdata()
{
cout<<"Rank:"<<rank;
}
};
int main()
{
student s;
s.getstudent(); //accessing base class member using derived
class object
s.inputdata();
s.showstudent(); // accessing base class member using derived
class object
s.outputdata();
s.modifydata();
s.showstudent();
s.outputdata();
}

OUTPUT:

16 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Name:John
Roll:10
Age:18
Rank:3
Name:John
Roll:10
Age:18
Rank:3
Do you want to modify?(Y/N):Y
Age:28
Rank:2
Name:John
Roll:10
Age:28
Rank:2

Multiple Inheritances

This is a single inheritance connected in parallel, having two or more base classes and a common
derived class. It has the tree structure. Here a class can inherit the properties of two or more
classes. The general format for declaring and defining a derived class from multiple base classes
is:

class derived : visibility base1, visibility base2,visibility base3,.....{ } ;

where, derived is the derived class name and base1,base2,base3,... are base class names.
Visibility is the access specifier used for the derivation. Generally it is public or private. No an
object of C, derived from the base classes A and B will have the feature of both A and B.

A B

Illustrate the multiple inheritance with public derivation

#include<iostream>

17 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

using namespace std;


class stud
{
private:
char name[20];
char roll[8];
protected:
int age;
public:
void input()
{
cout<<"Name:";
cin>>name;
cout<<"Roll:";
cin>>roll;
cout<<"Age";
cin>>age;
}
void output()
{
cout<<endl<<"Name:"<<name<<endl<<"Roll:"<<roll<<endl;
cout<<"Age:"<<age<<endl;
}
};
class academic
{
private:
int rank;
public:
void input()
{
cout<<"Rank:";
cin>>rank;
}
void output()
{
cout<<"Rank:"<<rank;
}
};
class medical:public student,public academic
{
18 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

private:
char bloodgp[4];
public:
void cinput()
{
student::input(); // input()invoked along with class name
academic::input();
cout<<"Blood Group:";
cin>>bloodgp;
}
void coutput()
{
student::output(); // output()invoked along with class name
academic::output();
cout<<endl<<"Blood Group:"<<bloodgp<<endl;
}
};
void main()
{
medical m;
cout<<"Enter student Details:"<<"\n";
m.cinput();
cout<<"\n Details of a student:"<<"\n";
m.coutput();
}

OUTPUT:

Enter Student Details:


Name:Rahul
Roll:303
Age:18
Rank:2
Blood Group:O+

Details of a Student:
Name:Rahul
Roll:303
Age:18
Rank:2
Blood Group:O+

Multi-Level Inheritance

19 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

A chain of single inheritance is referred to as multilevel inheritance.

Z
In this type of inheritance, class B plays a dual role and act both as a derived class as well as a
base class. When the class B is inherited from class A, B is acting as a derived class. When the
class C is derived from the class B, B is acting as a base class for the derived class C. The class
C holds the characteristics of both the classes, namely class A and class B, which in turn directs
the user to reuse the definitions made in those two classes.

if (class B is inherited from A under the public access specifier) then


class C will contain the public member of both class A and B
else
class C will contain only the public member of B

the above statement clearly mentions the position of C, when the inheritance of B from A is
public or not . In any type of derivation, the protected members of the class A will be visible to
the public members of classes B only and class C can never access them.

Illustrate the program for multiple inheritance with public

#include<iostream>
using namespace std;
class stud
{
private:
char name[20];
char roll[8];
protected:
int age;
public:
void getstudent()
{
cout<<"Name:";
cin>>name;
cout<<"Roll:";
cin>>roll;
cout<<"Age";

20 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

cin>>age;
}
void showstudent()
{
cout<<endl<<"Name:"<<name<<endl<<"Roll:"<<roll<<endl;
cout<<"Age:"<<age<<endl;
}
};
class student:public stud
{
private:
int rank;
public:
void inputdata()
{
cout<<"Rank:";
cin>>rank;
}
void modifydata()
{
char bool;
cout<<endl<<"Do you want to modify?(y/N):";
cin>>bool;
if(bool=='Y')
{
cout<<"Age:";
cin>>age;
cout<<"Rank:";
cin>>rank;
}
}
void outputdata()
{
cout<<"Rank:"<<rank;
}
};
class medical : public students
{
private:
char bloodgp[4];
public:
void cinputdata()
{
inputdata();
cout<<"Blood Group:";
cin>>bloodgp;
}
21 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

void coutputdata()
{
outputdata();
cout<<endl<<"Blood Group:"<<bloodgp<<endl;
}
};
void main()
{
medical m;
m.cinputdata();
m.coutputdata();
m.modifydata();
m.coutputdata();

OUT PUT:

Name:cnu
Roll:10
Age:15
Rank:8
Blood Group:B+

Name:cnu
Roll:10
Age:15
Rank:8
Blood Group:B+
Do you want to modify?(Y/N) Y
Age:19
Rank:3

Name:cnu
Roll:10
Age:19
Rank:3
Blood Group:B+

Hierarchical Inheritance

22 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

This is single inheritance connected in parallel keeping the base class common. Here classes B
and C have no connection; they only inherit from the common base class A. if an object of class
B only is created in the main() function, then there will be no trace of the features of class C and
vice versa.

B C

Illustrates Hierarchical inheritance and public derivation

#include<iostream>
using namespace std;
class stud
{
private:
char name[20];
char roll[8];
protected:
int age;
public:
void getstudent()
{
cout<<"Name:";
cin>>name;
cout<<"Roll:";
cin>>roll;
cout<<"Age";
cin>>age;
}
void showstudent()
{
cout<<endl<<"Name:"<<name<<endl<<"Roll:"<<roll<<endl;
cout<<"Age:"<<age<<endl;
}
};
class student:public stud

23 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

{
private:
int rank;
public:
void inputdata()
{
cout<<"Rank:";
cin>>rank;
}
void outputdata()
{
cout<<"Rank:"<<rank;
}
};
class medical:public students
{
private:
char bloodgp[4];
public:
void cinputdata()
{
inputdata();
cout<<"Blood Group:";
cin>>bloodgp;
}
void coutputdata()
{
outputdata();
cout<<endl<<"Blood Group:"<<bloodgp<<endl;
}
};
void main()
{
academic a;
cot<<"Enter the values of the object of academic:"<<"\n";
a.getstudent();
a.cinputdata();
cout<<"Contents of the object of academic:"<<"\n";
a.showstudent();
a.coutputdata();

24 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

//Objects are accessed using same method name


medical b;
cout<<"Enter the values of the object of edical:"<<"\n";
b.getstudent();
b.cinputdata();
cout<<"Contents of the object of medical:"<<"\n";
b.showstudent();
b.coutputdata();
}

Output:

Enter the values of the object of academic:


Name :Sai
Roll:101
Age:28
Rank:4
Content of the object of academic:
Name :Sai
Roll:101
Age:28
Rank:4

Enter the values of the object of academic:


Name :Sai ram
Roll:202
Age:18
Blood Group: O+
Content of the object of academic:
Name :Sai ram
Roll:202
Age:18
Blood Group: O+

Hybrid Inheritance

25 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Hybrid inheritance is a combination of two or more types of inheritance. In some applications


user may need to combine the features available in multilevel inheritance, hierarchical
inheritance and multiple inheritance.

B C

One may, very well observe that this is a combination of multilevel and multiple inheritance

Illustrates the implementation of hybrid inheritance.

#include<iostream>
using namespace std;
class student
{
private:
char name[20];
char roll[8];
protected:
int age;
public:
void getstudent()
{
cout<<"Name:";
cin>>name;
cout<<"Roll:";
cin>>roll;
cout<<"Age";
cin>>age;
}
void showstudent()
{
cout<<endl<<"Name:"<<name<<endl<<"Roll:"<<roll<<endl;
cout<<"Age:"<<age<<endl;
}
};
class academic:public student

26 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

{
private:
int rank;
public:
void inputdata()
{
getstudent();
cout<<"Rank:";
cin>>rank;
}
void outputdata()
{
showstudent();
cout<<"Rank:"<<rank;
}
};
class sports
{
private:
int score;
public:
void getscore()
{
cout<<"Score:";
cin>>score;
}
void putscore()
{
cout<<"score:"<<score;
}
};
class final:public academic,public sports
{
private:
char bloodgp[4];
public:
void fininputdata()
{
coiut<<"Blood Group:";
cin>>bloodgp;
}
void finoutputdata()
{
cout<<endl<<"Blood Group:"<<bloodgp<<endl;
}
};

27 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

int main()
{
final m;
cout<<"Enter student Deatails:"<<"\n;
m.inputdata();
m.getscore();
m.fininputdata();
cout<<"Student Details:"<<"\n";
m.outputdata();
m.putscore();
m.finoutputdata();
}

OUTPUT:
Enter student Details:
Name: Stroustrup
Roll:11
Age:18
Rank:10
Score:55
Blood Group:A+

Student Details:
Name: Stroustrup
Roll:11
Age:18
Rank:10
Score:55
Blood Group:A+

Virtual Base Classes

In the case of multiple inheritance, we have seen that ambiguity occurs when we use same name
for different functions in two or more base classes.

28 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Abstract Classes

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

Characteristics of abstract class


1. Abstract class cannot be instantiated, but pointers and references of Abstract class type
can be created.
2. Abstract class can have normal functions along with a pure virtual functions.
3. Abstract classes are mainly used for up casting, so that its derived classes can use its
interface.
4. Classes inheriting an abstract class must implement all pure virtual functions, or else they
will become abstract too.

Constructors in Derived Classes

Constructors are used to initialize data members in an object and also for allocating memory for
the objects. In the case of inheritance, the objects of the derived class are usually used instead of
the base class objects. Hence objects of the derived class are initialized using constructors and if
there is a need, the base class objects are also initialized using derived class constructors

When a base class and a derived class both have constructors and destructor functions, the
constructor functions are executed in the order of derivation. That is, the base class constructor is
executed before the constructor in the derived class.

The destructor functions are executed in the reverse order. That is, the derived class destructor is
executed before the base class destructor. Further arguments can be passed from the derived
class constructor to the base class constructor. The syntax for passing arguments from derived
class constructor is:

derived(arg-list):base(arg-list)
{
//body of the derived class constructor
}

Where, derived is the name of the derived class, base is the name of the base class, and the
argument lists in the two constructors can be same or different. when they are different, we must
pass to the derived class constructor all arguments need by both the derived class and the base
class. Then the derived class simply passes to the base class all those arguments required by it.

29 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

In the case of multiple inheritance, the constructors are executed i tneh order based classes are
specified. Destructors are expected in the reverse order. The general syntax for derived class
constructor in the case of multiple inheritance is:
derived (arg-list): base 21(arg-list),base2(arg-list),...
{
// body of the derived class constructor
}
where, derived is the name of the derived class and base1,base2,.... are the names of the base
classes. the argument list in the derived class constructor consists of all arguments needed by the
derived class and all the base classes.

// This program illustrates order of execution of constructors and destructors in the base class and
the //derived class. Both the constructors use the same arguments.

#include<iostream>
using namespace std;
class base
{
int i;
public:
base(int n)
{
cout<<"Constructing base class\n";
i=n;
}
~base()
{
cout<<"Destructing base clas\n";
}
void show()
{
cout<<"i="<<i<<"\n";
}
};
class derived:public base
{
int j;
public:
derived(int n):base (n)
{
cout<<"Constructing derived class\n";
30 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

j=n;
}
~derived()
{
cout<<"Destructing derived class \n";
}
void showj()
{
cout<<"j="<<j<<"\n";
}
};
void main()
{
derived ob(10);
ob.showj();
ob.showj();
}

Result:
constructing base class
constructing derived class
i=10
j=10
destructing derived class
destructing base class

31 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

Questions

1. What are the rules to be followed for declaring a copy constructor in a class
2. What are the advantages of dynamic constructor?
3. How is dynamic initialization of objects achieved?
4. What does ‟constructor with default arguments „mean?
5. Discuss the characteristics of a constructor function
6. What are the different types of constructors that can be created in a class? Explain with
suitable examples
7. Give an example of a class with copy constructor. Write a program that uses this copy
constructor.
8. Explain the different between overloaded constructors and construct with default
arguments.
9. What are the characteristics of destructor? Explain with a suitable explain program the
usage of new and delete operators in constructors and destructors.
10. Develop an object-oriented program to read the following information from the
keyboard. Employee name, employee code, designation, year of experience and age.
Construct the date base with suitable member function member functions for initializing,
displaying and for destroying the data
11. What does inheritance means?
12. State the advantages of inheritance
13. What is the need for inheritance?
14. How does the access specifiers „protected‟ differ from „private‟?
15. State the different types of inheritance.
16. Describe the syntax for single inheritance
17. Describe the syntax for multiple inheritances
18. Distinguish between multilevel and multiple inheritances
19. Define hierarchical inheritance
20. How is ambiguity in multiple inheritances resolved?
21. What does hybrid inheritance mean?
22. What is a virtual base class?
23. What is the ambiguity that call for declaring a class ‟virtual‟;
24. In what order are the constructors called when a derived class object is created
25. Discuss the base class access specifiers and the different types of derivations
26. Explain what „protected‟ means when referring to members of a class and when it issued
as an access control specifier for deriving a class
27. List the different types of inheritances and explain the suitable examples.
28. Discuss the construction and destruction of derived class and base classes
29. With a suitable example program, explain the use of „virtual‟ base class

32 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III

30. Discuss multiple inheritances with a suitable example


31. Discuss multilevel inheritance with a suitable example
32. Discuss hierarchical inheritance with a suitable example
33. What are the ambiguity present in multiple and hybrid inheritance? Explain how they
are resolved
34. When a base class is inherited as public by the derived class, what happens to its public
and Private members if the base class is inherited as private by derived class, what
happens to its public and private members? Explain with example programs.

33 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
UNIT-IV
Introduction to pointers, Pointers to Objects, Pointers to Derived Classes, compile time
polymorphism, Run time polymorphism, Virtual Functions, Pure Virtual Functions, Virtual of
binary and unary operators.
Files in C++: File I/O, Unformatted and Binary I/O.

Introduction to pointers

Pointer Definition: A memory variable that stores a memory address. These can have any name
that is legal for other variables, and it is declared in the same fashion like other variables but it is
always denoted by a „*‟ operator.
Declaration: In C++ , we can declare a pointer variable similar to other variables declaration.
The declaration is based on the data type of the variable it points to. The declaration of a pointer
variable takes the following format.
Syntax:
Data_type * pointer_variable ;
Here pointer_variable is the name of the pointer, and the data_type refers to one of the
C++ data types, such as int, float, char and class. The data_type is must followed by an asterisk
(*) symbol, which distinguishes a pointer variable from other variable to the compiler.
For example:
int *x; // integer pointer variable
float *f; // floating pointer variable
char *y; // character pointer variable
Here * is called as an indirection operator or dereference operator.
Here * is used in two ways, one is declaration and the other is to dereference.
declared * indicates it is not an ordinary variable.
dereference * indicates the value at the memory location.
Note: We can locate asterisk *) before the pointer variable, or between the data type and pointer
variable, or immediately after the data type.

-1- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
Initialization: Like other programming languages, a variable must be initialized before using it
in C++ program. We can initialize a pointer variable as follows.
For example:
int *ptr , a; // declaration
ptr=&a; // initialization
The „&‟ is the address of operator or reference operator. If the „&‟ operator immediately
precedes, the variable returns the address of it. In the above statement the pointer variable ptr,
contains the address of the variable a.
Example of using pointers:-
#include<iostream.h>
#include<conio.h>
void main( )
{
int a=10, *ptr1, *ptr2;
clrscr( );
ptr1= &a;
ptr2= &ptr1;
cout<<”The address of a:”<<ptr1<<endl; // or &a
cout<<”The address of ptr1:<<ptr2<<endl;
cout<<”The value of a:”<<a<<endl;
cout<<”The value of a through pointer variable ptr1 is:”<<*ptr1;
}
Output:
The address of a: ff44
The address of ptr1: ff66
The value of a: 10
The value of a through pointer variable ptr1 is: 10

Pointers to Objects
We can declare the pointer variable to user defined data type i.e class. We can also use pointer variable to
access the public members of a class like object.
The general format of pointer to object is:

-2- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
class_name obj;
class_name *ptr;
ptr = &obj;
Here the pointer variable ptr, contains the address of object obj of the same class.

For example:
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code=a;
price=b;
}
void show( )
{
cout<<”code: “<<code<<endl;
cout<<”price: “<<price<<endl;
}
}; // end of class

item x; // x is an object of class item


item *ptr; // ptr is pointer of type item
ptr=&x; // ptr contains the address of object x

We can refer the member functions of class item in two ways:


1) Dot ( . )operator and the object.
x.getdata(100,75,50);
x.show( );
2) Arrow ()operator and the object pointer.
-3- www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
ptrgetdata(100,75.50)
ptrshow( );

x.getdata(100,75,50); ptrgetdata(100,75.50)
OR
x.show( ); ptrshow( );

we can also create objects using new operator as follows:


item *ptr=new item;
ptrshow( );
we can also access array of objects:
item *ptr =new item[10];
creates memory space for array of objects of item.

Program: Illustrate the program for pointer to object


#include<iostream.h>
class Bill
{
int qty;
float price , amt;
public:
void getdata(int a, float b)
{
qty=a;
price=b;
amt=qty*price;
}
void show( )
{
cout<<”Quantity: ”<<qty<<endl;
cout<<”Price: ”<<price<<endl;

-4- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
cout<<”Amount:”<<amt;
}
};
int main( )
{
clrscr( );
Bill B; // object B is created
Bill *ptr = &B; //pointer variable declared and initialized
ptrgetdata(45,10.25);
ptrshow( );
return 0;
}
Output: Quantity: 45
Price: 10.25
Amount: 461.25

Pointers to Derived Classes

In general, a pointer of one type cannot point to an object of a different type. However, there is an
important exception to this rule , that relates only to derived class.
A base class pointer can be used to point to a derived object, the opposite is not true, i.e. A derived
class pointer may not point to a object of base class. The base class pointer can access only the member
functions of the derived class that were inherited from the base class, i.e. we won‟t be able to access any
members added by the derived class. You can typecast a base pointer into a derived pointer and gain full
access to the entire derived class.
For example, if B is a base class and D is a derived class from B, then a pointer declared as a pointer to B
can also be a pointer to D. Consider the following declarations:
B *bptr; // pointer to class B
B b; // base class object
D d; // derived class object
bptr = &b; // bptr points to object b
we can make bptr to point to the object d as follows:

-5- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
bptr = &d; // bptr points to object d
This is perfectly valid with C++ because d is an object derived from the class B.
However, there is a problem in using bptr to access the public members of the derived class D.
Using bptr, we can access only those members which are inherited from B and not the members that
originally belong to D.
In case a member of D has the same name as one of the members of B, then any reference to that
member by bptr will always access the base class member
BASE CLASS DERIVED CLASS

Members of Base

Members +

Members of Derived

Base Pointer Derived Pointer

/*program to illustrating the base class pointer points to derived class object*/
class BC
{
public:
int b;
void show( )
{
cout<<”b=”<< b <<endl;
}
};
class DC : public BC
{
public:
int d;

-6- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
void show( )
{
cout<<”b=”<< b<<endl<<”d=”<< d <<endl;
}
void sample( )
{
cout<< “This is own function of derived class:”;
}
};
int main( )
{
BC *bptr; // base class pointer
BC base; // base is object for class BC
bptr = &base; //base address
bptrb=100;
cout<<”bptr points to base object \n”;
bptrshow( );
DC derived; // derived class
bptr = &derived; // now base pointer points to derived object
bptrb=200;
//bptrd=300 //won’t work because this is original data of derived class
cout<<”bptr now points to derived object \n”;
bptrshow( );
// accessing d using a pointer of type derived class DC
DC *dptr;
dptr = &derived;
dptrd=300;
cout<<”dptr is derived type pointer”;
dptrshow( );
cout<<”using ((DC*)bptr) \n”;
((DC*)bptr)d=400; //typecast bptr to DC type
((DC*)bptr)show( );
return 0;
}

-7- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
OUTPUT:
bptr points to base object
b = 100
bptr now points to derived object
b=200
dptr is derived type pointer
b=200
d=300
using ((DC *)bptr)
b=200
d=400

Polymorphism
Polymorphism is one of the crucial features of OOP. It simply means „one name, multiple
forms’. We have already seen how the concept of polymorphism is implemented using the overloaded
functions and operators.
Mainly they are two types of polymorphism.

Types of Polymorphism in C++:


POLYMORPHISM

COMPILE TIME RUN TIME

OPERATOR FUNCTION VIRTUAL


OVERLOADING OVERLOADING FUNCTION

Compile time polymorphism


The overloaded member functions are „selected‟ for invoking by matching arguments, both type
and number. This information if known to the compiler at the compile time and, therefore, compiler is

-8- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
able to select the appropriate function for a particular call at the compile time itself. This is called early
binding or static binding. Also known as compile time polymorphism, early binding means that an
object is bound to its function call at compile time.

Run time polymorphism

Binding in C++:
class Base //base
{
int b;
public:
void display( ) //base member function
{
}
};
class Derived: public Base //derived
{
int d;
public:
void display( ) //derived member function
{
}
};
How do we use the member function display( ) to display the values of objects of both the classes
Base and Derived?. Since the prototype of display( ) is the same in both the places, the function is not
overloaded and therefore static binding does not apply. We have seen earlier that, in such situations, we
may use the class resolution operator to specify the class while invoking the functions with the derived
class objects.
It would be nice if the appropriate member function could be selected while the program is
running. This is known as run time polymorphism. How could it happen?
C++ supports a mechanism known as virtual function to achieve run time polymorphism.
At run time, when it is known what class objects are under consideration, the appropriate version
of the function is invoked. Since the function is invoked with a particular class much later after the

-9- www.eduwing.blogspot.in by M.A.Srinuvasu


Object Oriented Programming with C++ UNIT-IV
compilation, this process is termed as late binding. It is also known as dunamic binding because the
selection of the appropriate function is done dynamically at run time.
Dynamic Binding is one of the powerful features of C++. This requires the use of pointers to
objects. We shall discuss in detail how the object pointers and virtual functions are used to implement
dynamic binding.
Virtual Functions
Poly means many or multiple, morphy means to change from one state to another, ism means the
process of something. In C++, polymorphism is implemented in three different ways. These are function
overloading, operator overloading and virtual functions.
In C++, a function call can be bound to the actual either at compile time or at runtime. Resolving a
function call at compile time is known as compile time polymorphism or early binding or static binding.
Where as, resolving a function call at runtime is known as runtime polymorphism or late binding or
dynamic binding. Runtime polymorphism allows postponing the decision of selecting the suitable
member functions until runtime. In C++, this is achieved by using virtual functions.In C++, runtime
polymorphism is implemented by using virtual member functions.
When we use the same function name in both the base and derived classes, the function in base
class is declared as virtual function using the keyword „virtual’ preceding its normal declaration. When
the function is made virtual,C++ determines which function to use at run time based on the type of object
pointed to by the base pointer, rather than the type of the pointer.
Virtual functions allow programmers to declare functions in a base class, which can be in each
derived class. A virtual function is a member function that is declared within a base class and redefined
by a derived class.
When a base pointer points to a derived object that contains a virtual function, C++
determines which version of that function to call based up on the type of object pointed to by the pointer.
This determination is made at runtime.
Virtual means existing in appearance but not in reality.
Syntax: virtual function_name( arguments list )
{
Body of function
}
Program: Illustrate the Virtual Functions
#include<iostream.h>
class Base //Base

- 10 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
{
public: void display( )
{
cout<<”\n Base Class Display Function”;
}
virtual void show( )
{
cout<<”\n Base Class Show Functon”;
}
};
class Derived: public Base //derived
{
public:
void display( )
{
cout<<”\n Derived Class Display Function”;
}
void show( )
{
cout<<”\n Derived Class Show Function”;
}
};
int main( )
{
Base B;
Base *bptr;
Derived D;
cout<<”\n bptr points to Base object “;
bptr = &B;
bptr -> display( ); //Calls Base Version
bptr ->show( ); //Calls Base Version
cout<<”\n Now bptr points to Derived object”;
bptr = &D;
bptr -> display( ); //Calls Base Version

- 11 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
bptr -> show( ); //Calls Derived Version
return 0;
}
Output: bptr points to Base object
Base Class Display Function
Base Class Show Function
Now bptr points to Derived object
Base Class Display Function
Derived Class Show Function
When bptr is made to point to the object D, the statement
bptr -> display ( );
calls only the function associated with the Base ( i.e Base::display( ) ), whereas the statement
bptr ->show( );
calls the Derived version of show( ). This is because the function display( ) has not been made
virtual in the Base class.
NOTE: One important point to remember is that, we must access virtual function through the use of a
pointer declared as a pointer to the base class. Why can‟t we use the object name (with the dot operator)
the same way as any other member function to call the virtual functions? We can, but remember, run time
polymorphism is achieved only when a virtual function is accessed through a pointer to the base class.

Rules for virtual functions:


When virtual functions are created for implementing late binding, we should observe some basic
rules that satisfy the compiler requirements:
The virtual function must be members of some class.
They cannot be static members.
They are accessed by using object pointers.
A virtual function in a base class mist be defined, even though it may not be used.
We cannot have virtual constructors, but we can have virtual destructors.

Pure Virtual Functions

For the virtual function the member function of base class should be prefixed by keyword virtual.

- 12 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
class base
{
public:
virtual void display( );
};

Since the function display in the base class never gets executed. We can do away with the body if
this virtual function and add notation”=0”, in the function declaration as shown below:

class base
{
public:
virtual void display( )=0;
};

The display( ) function is known as a virtual function, thus a pure virtual function is a virtual
function with no body and is = 0 in its declaration. The zero which is assigned to the virtual function
simply tell to the compiler that a function will be pure i.e. it will not have any body.
Since display( ) if the base class was never getting called we made it a pure virtual function. In
another side for this we may want that a user should never be able to create an object of the base class. As
stated earlier, such classes are called abstract base classes. The main objective of an abstract base class
is to provide some traits to the derived classes and to create a base pointer required for achieving run time
polymorphism.

Virtual of binary and unary operators


There are two types of operator overloading:
Unary operator overloading
Binary operator overloading

Operator Name Type

! Logical NOT Unary

- 13 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

& Address-of Unary

() Cast Operator Unary

* Pointer dereference Unary

+ Unary Plus Unary

++ Increment Unary

– Unary negation Unary

Decrement 1
–– Unary

~ complement Unary

, Comma Binary

!= Inequality Binary

% Modulus Binary

%= Modulus assignment Binary

& Bitwise AND Binary

&& Logical AND Binary

&= Bitwise AND assignment Binary

* Multiplication Binary

*= Multiplication assignment Binary

- 14 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

+ Addition Binary

+= Addition assignment Binary

– Subtraction Binary

–= Subtraction assignment Binary

–> Member selection Binary

–>* Pointer-to-member selection Binary

/ Division Binary

/= Division assignment Binary

< Less than Binary

<< Left shift Binary

<<= Left shift assignment Binary

<= Less than or equal to Binary

= Assignment Binary

== Equality Binary

> Greater than Binary

>= Greater than or equal to Binary

>> Right shift Binary

- 15 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

>>= Right shift assignment Binary

^ Exclusive OR Binary

^= Exclusive OR assignment Binary

| Bitwise inclusive OR Binary

|= Bitwise inclusive OR assignment Binary

|| Logical OR Binary

Whenever an unary operator is used, it works with one operand, therefore with the user defined data
types, the operand becomes the caller and hence no arguments are required.

Take a look at the following unary operator overloading example, in this case the unary operators
increment (++) and decrement (–):
#include<iostream>
using namespace std;

//Increment and decrement overloading


class Inc {
private:
int count ;
public:
Inc() {
//Default constructor
count = 0 ;
}

Inc(int C) {
// Constructor with Argument
count = C ;

- 16 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
}

Inc operator ++ () {
// Operator Function Definition
return Inc(++count);
}

Inc operator -- () {
// Operator Function Definition
return Inc(--count);
}

void display(void) {
cout << count << endl ;
}
};

void main(void) {
Inc a, b(4), c, d, e(1), f(4);

cout << "Before using the operator ++()\n";


cout << "a = ";
a.display();
cout << "b = ";
b.display();

++a;
b++;

cout << "After using the operator ++()\n";


cout << "a = ";
a.display();
cout << "b = ";

- 17 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
b.display();

c = ++a;
d = b++;

cout << "Result prefix (on a) and postfix (on b)\n";


cout << "c = ";
c.display();
cout << "d = ";
d.display();

cout << "Before using the operator --()\n";


cout << "e = ";
e.display();
cout << "f = ";
f.display();

--e;
f--;

cout << "After using the operator --()\n";


cout << "e = ";
e.display();
cout << "f = ";
f.display();
}

As mention before the overloaded operator function above is an example of unary operator
overloading. But you may have notice that when compiling the compiler will give some
warnings. For example in Visual C++ the warnings will look something like this:

warning C4620: no postfix form of 'operator ++' found for type 'Inc', using prefix form

- 18 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

As you can see the postfix (b++) overloaded function can not be found so the prefix (++a) is
used by the compiler. What we need are two operator overloaded functions of the exact same
signature. Bjarne Stroustrup has provided the solution by introducing the concept of dummy
argument, so that it becomes function overloading for the operator overloaded functions. Take a
look at the example:

#include<iostream>
using namespace std;

//Increment and decrement overloading


class Inc {
private:
int count ;
public:
Inc() {
//Default constructor
count = 0 ;
}

Inc(int C) {
// Constructor with Argument
count = C ;
}

Inc operator ++ () {
// Operator Function Definition
// for prefix
return Inc(++count);
}

Inc operator ++ (int) {

- 19 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
// Operator Function Definition
// with dummy argument for postfix
return Inc(count++);
}

Inc operator -- () {
// Operator Function Definition
// for prefix
return Inc(--count);
}

Inc operator -- (int) {


// Operator Function Definition
// with dummy argument for postfix
return Inc(count--);
}

void display(void) {
cout << count << endl ;
}
};

int main() {
Inc a, b(4), c, d, e(1), f(4);

cout << "Before using the operator ++()\n";


cout << "a = ";
a.display();
cout << "b = ";
b.display();

++a;
b++;

- 20 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

cout << "After using the operator ++()\n";


cout << "a = ";
a.display();
cout << "b = ";
b.display();

c = ++a;
d = b++;

cout << "Result prefix (on a) and postfix (on b)\n";


cout << "c = ";
c.display();
cout << "d = ";
d.display();

cout << "Before using the operator --()\n";


cout << "e = ";
e.display();
cout << "f = ";
f.display();

--e;
f--;

cout << "After using the operator --()\n";


cout << "e = ";
e.display();
cout << "f = ";
f.display();

return 0;
}

- 21 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

As you can see in this case we use int as a dummy argument for post-fix, when we redefine the
functions for the unary increment (++) and decrement (--) overloaded operators. You must
remember that int isn't an integer, but just a dummy argument. You can see it as a signal to the
compiler to create the post-fix notation of the operator.

Whenever a binary operator is used - it works with two operands, therefore with the user defined
data types - the first operand becomes the operator overloaded function caller and the second is
passed as an argument. This results in compulsion of receiving one argument in overloading of
the binary operators. Let's look at an example of binary operator overloading:

#include<iostream>
using namespace std;

class Rational
{
private:
int num; // numerator
int den; // denominator
public:
void show();
Rational(int=1,int=1);
void setnumden(int,int);
Rational add(Rational object);
Rational operator+(Rational object);
bool operator==(Rational object);
bool operator!=(Rational object);
};

void Rational::show() {
cout << num << "/" << den << "\n";
}

- 22 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

Rational::Rational(int a,int b) {
setnumden(a,b);
}

void Rational::setnumden(int x,int y) {


int temp,a,b;
a = x;
b = y;
if(b > a) {
temp = b;
b = a;
a = temp;
}
while(a != 0 && b != 0) {
if(a % b == 0)
break;
temp = a % b;
a = b;
b = temp;
}
num = x / b;
den = y / b;
}

Rational Rational::add(Rational object) {


int new_num = num * object.den + den * object.num;
int new_den = den * object.den;
return Rational(new_num, new_den);
}

Rational Rational::operator+(Rational object) {


int new_num = num * object.den + den * object.num;

- 23 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
int new_den = den * object.den;
return Rational(new_num, new_den);
}

bool Rational::operator==(Rational object) {


return (num == object.num && den == object.den);
}

bool Rational::operator!=(Rational object) {


return (num != object.num || den != object.den);
}

int main() {
Rational obj1(1,4), obj2(210,840), result1;
result1 = obj1.add(obj2);
result1.show();

Rational obj3(1,3), obj4(33,99), result2;


result2 = obj3 + obj4;
result2.show();

Rational obj5(10,14), obj6(25,35), obj7(2,3), obj8(1,2);

if(obj5 == obj6) {
cout << "The two fractions are equal." << endl;
}
if(obj7 != obj8) {
cout << "The two fractions are not equal." << endl;
}
return 0;
}

- 24 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
As you can see we used the binary operator plus (+), equal (==) and not-equal (!=) and all
function work with two operands. The first (Rational) is the operator overloaded function caller
and the second (object) is the passed argument.

- 25 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

File I/O
A stream is a general name given to a flow of data. In C++, an object of a particular class
represents a stream. C++ uses file stream as an interface between the program and the files. The
stream that supplies data to the program is input stream and the one that receives data from the
program is output stream.
We have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively.
To read and write from a file, this requires another standard C++ library called fstream, which
defines three new data types:
Data Type Description
ofstream This data type represents the output file stream and is used to create files
and to write information to files.
ifstream This data type represents the input file stream and is used to read
information from files.
fstream This data type represents the file stream g enerally, and has the capabilities
of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
ios

istream ostream

iostream

ifstream fstream ofstream

- 26 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
ofstream: contain open() with default output mode. Inherits the functions put(), seekp(),
tellp() and write() from ostream.
ifstream: contain open() with default input mode. Inherits the functions get(), getline(),
seekg(),tellp() and read() from istream.
fstream: contain open() with default input mode. Inherits all functions from istream and
ostream classes through iostream.

Opening a File:
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.
Mode Flag Description

ios::app Append mode. All output to that file to be appended to the end.
ios::ate Open a file for output and move the read/write control to the end of
the file.
ios::in Open a file for reading .
ios::out Open a file for writing .
ios::trunc If the file already exists its contents will be truncated before
opening the file.
ios::binary Open in binary mode

- 27 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
You can combine two or more of these values by ORing them tog ether. 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 mfile;
mfile.open("file.dat", ios::out | ios::trunc );
Similar way, you canopena file for reading and writing purpose as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );

// Illustrate opening a file and writing a sentence into it


#include<iostream>
#include<fstream>
using namespace std;
void main()
{ ofstream mfile;
mfile.open(“Example.txt”,ios::out);
mfile<<”Writing this sentence into this file. \n”;
mfile.close();
}

Default modes

Each one of the open() member functions of the classes ofstream, ifstream and fstream has a
default mode that is used if the file is opened without a second argument. For the ifstream class,
ios::in is automatically assumed, even if a mode that does not include it is passed as second
argument to the open() member function. Similarly for the ofstream class, ios::out is
automatically assumed. The default value is applied only if the function is called without
specifying any value for the mode parameter. If the function is called with any value in that
parameter the default mode is overridden, but not combine.

- 28 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
class Default Mode
ofstream ios::out
ifstream ios:: in
fstream ios:: in| ios:: out

File stream opened in binary mode perform input and output operations independently of any
format considerations. Non-binary files are known as text files. Since the first operation
performed on a file stream object is generally to open a file, the three stream classes include a
constructor that automatically call the open() member function. Object construction and stream
opening can be combined in a single statement. Therefore, one could also have declared the
object mfile and conducts the file opening operation with the constructor by writing:
ofstream mfile(“example.bin”,ios::out|ios::app|ios::binary);
The function is_open()
To check if a file stream was successful in opening a file, the member function is_open() with no
arguments is used. This is a member function of an object of the ofstream. It returns a bool value
true in case the stream object is associated with an open file, and false otherwise.
For example
if(mfile.is_open()) //mfile is an ofstream object
{
mfile<<”This is the first line.\n”; //writing on the file
}
else
cout<<”file not open”; //the sting appears on the display

Closing a File
When a C++ prog ram terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a g ood practice that a prog
rammer should close all the opened files before prog ram termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream,
and ofstream objects.

- 29 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
void close();

Writing to a File:
While doing C++ prog ramming , you write information to a file from your prog ram 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 prog ram 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++ prog ram which opens a file in reading and writing mode. After writing
information inputted by the user to a file named afile.dat, the prog ram reads information from
the file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;

int main ()
{

char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;

- 30 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
cout << "Enter your age: ";
cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}

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

- 31 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
9
Above examples make use of additional functions from cin object, like getline() function to read
the line from outside and ignore() function to ignore the extra characters left by previous read
statement

Static flags
There are few member functions included in the stream objects that can be used to extract
information about the static of a file.

bad() Returns true if a reading or writing operation fails. For example, in the case
that we try to write to a file that is not open for writing or if the device where
we try to write has no space left
fail() Returns true in the same cases as bad(), but also in the case that a format error
happens, like when an alphabetical character is extracted when we are trying to
read an integer number.
eof() Returns true if a file open for reading has reached the end
good() It is the most generic state flag: it returns false in the same cases in which
calling any of the previous functions would return true.
Note that good and bad are not exact opposites (good checks more state flags
at once).
clear() In order to reset the state flags checked by any of those member functions
discussed above, the member function clear() is used . It takes no parameters

Get and Put Stream pointers

The input/output stream objects have one internal stream pointer. The ifstream has a pointer get,
which points to the element to be read in the next input operation. Similarly the ofstream has a
pointer put, which point points to the location where the next element has to be written. Both the
get and put pointers are inherited by the fstream from the iostream. The „pointer‟ in this context
should not be confused with normal C++ pointers used as address variables. These values simply
specify the byte number in the file where writing or reading will take place.
- 32 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
tellg() and tellp()
These two member functions admit no parameters and return a value of type pos_type
(according ANSI-C++ standard) that is an integer data type representing the current position
of get stream pointer (in case of tellg) or put stream pointer (in case of tellp).

seekg() and seekp()


This pair of functions serve respectively to change the position of stream pointers get and put.
Both functions are overloaded with two different prototypes:
seekg ( pos_type position );
seekp ( pos_type position );
Using this prototype the stream pointer is changed to an absolute position from the beginning of
the file. The type required is the same as that returned by functions tellg and tellp.
seekg ( off_type offset, seekdir direction );
seekp ( off_type offset, seekdir direction );
Using this prototype, an offset from a concrete point determined by parameter direction can be
specified. It can be:
ios::beg offset specified from the beginning of the stream
ios::cur offset specified from the current position of the
stream pointer
ios::end offset specified from the end of the stream

The values of both stream pointers get and put are counted in different ways for text files than for
binary files, since in text mode files some modifications to the appearance of some special
characters can occur. For that reason it is advisable to use only the first prototype
of seekg and seekp with files opened in text mode and always use non-modified values returned
by tellg or tellp. With binary files, you can freely use all the implementations for these functions.
They should not have any unexpected behavior.

- 33 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV

Unformatted and Binary I/O


TEXT FILES
Non binary files are known as text files. They do not include the ios::binary flag in their
opening mode. These files are designed to store text. All values that we input or output are likely
to suffer some formatting transformations, which do not necessarily correspond to their literal
binary value. Data output operations on text files are performed in the same way as we work with
cout. Similarly data input from text file can be performed in the same way as we do with cin.
get() and put() functions
The ifstream member function get() reads a character from a specified file. The ofstream member
function put() writes a character into a specified output stream.
Program: textfile.cpp
//This program illustrates opening a text file and writing few lines into it.
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream mfile(“example.txt”); //opening file for output
if(mfile.is_open())
{
mfle<<”this is the first line./n”; //writing on the file
mfile<<”this isthe second line./n”;
mfile.close(); //closing the file
}
else
cout<<”unable to open the file”;
}
Program: textfile0.cpp
//This program illustrates reading a text from keyboard and writing it on a specified file
#include<iostream>
#include<fstream>
#include<iomanip.h>
#define max 2000

- 34 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
void main()
{
Ofstream mfile; //defining the file object for input
char fname[10],line[max];
cout<<”enter the name of file to be opened .\n”;
cin>>fname;
mfile.open(fname);
cout<<”enter text and terminate with @\n”;
cin.get(line ,max,’@’);
cout<<”get input is:\n”;
cout<<line;
cout<<”storing onto file:”<<fname<<”\n”;
mfile<<line; //writing on the line
mfile.close(); //closing the file
}
Program text file1.cpp
#include<iostream>
#include<fstream>
#include<string.h>
void main()
{
string line;
ifstream mfile(“example.txt”); //opening file for input
if(mfile.is_open())
{
while(!mfile.eof())
{
getline(mfile,line); //reading th contents of file
cout<<line<<endl; //displaying the contents
}
mfile.close(); //closing the file
}
else

- 35 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
cout<<”unable to open the file”;
}
Program textfile2.cpp
//This program illustrates reading a text file character by character and
// display the contents on the screen.
#include<iostream>
#include<stdlib.h>
void main()
{
ifstream mfile; //opening a file for input
char fname[10],ch;
cout<<”enter the name of file to be opened”;
cin>>fname;
mfile.open(fname); //opening the file
if(mfile.fail())
{
cout<<”no such file exists\n”;
exit(1);
}
while(!mfile.eof())
{
ch=(char)mfile.get(); //reading the contents of file
cout.put(ch); //displaying the content
}
mfile.close(); //closing a file
}
BINARY FILES:
Binary files are the file streams opened in the mode ios::binary. They perform
input and output operations independently of any format considerations. There is no need to
format any data, and data may not use the separation codes (like space, newline, etc…) used by
text files, to separate elements. Hence, in binary files, input and output data with the extraction
and insertion operators (<< and >>) and functions like getline are not efficient.

- 36 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
Binary files are used to store programs and data. Binary files can be classified in the
way they are accessed – Sequential access files and Direct (or random) access files. To input
and output binary data sequentially, file streams contain two member functions write() and
read(). The function write() is a member function of ostream inherited by ofstream and read() is
a member function of istream that is inherited by ifstream. Objects of class fstream contain both
the functions. Their prototypes are:
write(memory_block, size);
read(memory_block, size);
Where memory block is of type “pointer to char” (char*), and represents the address of an array
of bytes where the read data elements are stored from where the data elements to be written are
taken. The size parameter is an integer value that specifies the number of characters to be read
form the memory block or the number of characters to be written to the memory block. One can
also use these functions to write and read class objects in a file.

Files

Text Binary

Program Data

Fig: Classification of files


Sequential Random

CLASSES AND FILE OPERATIONS:


In order to write an object obj of a class into a file the following format is used.
mfile.write( (char*) &obj,sizeof(obj) );
where mfile is a fstream object.
Similarly, in order read an object obj of a class from a file the following format is used.
mfile.write( (char*) &obj,sizeof(obj) );
Program: This program illustrates writing class objects into a file and reading the same.

- 37 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
#include<conio.h>
class studentinfo
{
protected:
char name[20],sex;
int age;
float height,weight;
public:
void getdata();
void display();
};

void studentinfo : : getdata()


{
cout<<”enter the following information: \n”;
cout<<”name:”; cin>>name;
cout<<”Age:”; cin>>age;
cout<<”Sex:”; cin>>sex;
cout<<”height:”; cin>>height;
cout<<”weight:”; cin>>weight;
}

void studentinfo : : display()


{
cout<<name<<setw(5)<<age<<<<endl;
cout<<sex<<setw(5)<<height<<setw(5)<<weight<<endl;
}
void main()
{
clrscr();

- 38 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
studentinfo obj;
fstream mfile;
char fname[10];
cout<<”enter a file name: \n:”;
cin>>fname;
obj.getdata(); //reading an object from the keyboard
mfile.open(fname, ios : : out);
cout<<”writing data into the file……….\n”
mfile.write( (char*) &obj , sizeof(obj) ); //writing the object into the file
mfile.close();
mfile.open(fname, ios : : in);
cout<<”reading data from the file………..\n”;
mfile.read( (char*) & obj, sizeof(obj) ); //reading the object from the file
obj.display();
mfile.close();
getch();
}
The above program contains a class studentinfo with two functions getdata() and display(). An
object obj of type studentinfo is created and the data in the object, received from the keyboard,
is written in a file opened in output mode ios : : out, the name of the file being chosen at
runtime.
The file is then closed and opened again in the input mode ios : : in. The data in the object
obj stored earlier is then read from the file and displayed.

- 39 - www.eduwing.blogspot.in by M.A.Srinuvasu
Important Questions

UNIT-I

1. Enumerate and explain the advantages of Object Oriented Programming.


2. Briefly explain the identifiers and constants used in C++.
3. What are the derived data types available in C++? Explain with suitable
examples.
4. Write short notes on the following with necessary examples.
a. Objects, classes.
b. Data abstraction and encapsulation.
c. Inheritance and polymorphism.
d. Dynamic binding and message passing.
5. Enumerate and explain the applications of object oriented programming.
6. Distinguish between procedure oriented programming and object oriented
programming
7. List at least four different constructs in C++ to define user defined data
types. Identify the mathematical principles behind these constructs
8. Define scope of variables in C++. What is the need for scope resolution
operator in C++?
9. Define the class. Explain its scope
10. Write a C++ program with dynamic initialization of variables
11. Define the structure of C++ program
12. Write a C++ program that illustrates the working of a reference variable
13. Write a program in C++ to concatenate two strings, find the length of a
string, find the substring
14. Discuss the features of Object Oriented Programming
15. Explain the structure of a C++ program
16. Write a short notes on reference variables
17. Discuss an approach to the development of procedure- oriented programs
18. Describe, with examples, the uses of enumeration data types
19. How are data and functions organized in an object-oriented Program?
20. What do you mean by dynamic initialization of a variable? Explain with an
example
21. What are fundamental characteristics of O O languages? Give examples.
22. Describe enumerated data types in C++. Do they differ from the usage in C?
Explain.
23. Describe the software evolution in C++.
24. Describe conditional operators in C++. Give examples.

www.eduwing.blogspot.in
Important Questions

UNIT-II

1. What are the advantages of function prototypes in C++?


2. When do we need to use default arguments in a function?
3. What is a class? How does it accomplish data hiding?
4. What is a friend function? What are the merits and demerits of using friend
function?
5. Describe the different styles of writing prototypes.
6. What is the main advantage of passing arguments by reference?
7. How does a C++ structure differ from a C++ class?
8. How is a member function of a class defined?
9. What is an inline function? What is its purpose? Why should in line
functions be used in C++ programs?
10. What are access specifiers? What is their purpose?
11. What is a friend function? Give example
12. Define a class for rational numbers and overload the operators + and * to
add and multiply rational numbers
13. Give a detailed description of Friend function and explain it with an
example
14. What is the use of this pointer, illustrate with the help of an example
15. Write a program in C++ that explains the dynamic allocation of a two-
dimensional array
16. Compare overloaded function versus overridden function
17. Explain Friend Functions
18. Explain parameter passing mechanisms in C++
19. What is a class? Explain its structure
20. Write a program to read a floating point number and to print its floor,
ceiling and the floating point number rounded to two decimal digits
21. Write a template class for array and write a function for searching for an
object X in the array ‘A’
22. What are the advantages of function prototypes in C++?
23. How does a C++ structure differ from a c ++ class?
24. What is the main advantage of passing arguments by reference?
25. Explain overloading unary and binary operator with an example
26. What are reference variables in C++? What is an in line function?
27. Describe the runtime memory management followed in C++.
28. Write a program in C++ to read double numbers until end-of-file and
without storing them in an array-like structure, to find their average and
standard deviation.

www.eduwing.blogspot.in
Important Questions

UNIT-III

1. What is a constructor? Is it mandatory to use constructors in a class?


2. Describe the importance of destructors.
3. Describe the syntax of multiple inheritance. When do we use such an
inheritance?
4. When do we make a class virtual? What is an abstract class?
5. List some of the special properties of constructor functions.
6. Define destructors. Explain what are its uses?
7. Describe the syntax of single inheritance in C++.
8. When do we use the protected visibility specifier to a class member?
9. Explain container class in C++
10. What are abstract classes? Give examples
11. Write rules for operator overloading
12. What is meant by inheritance? How is it useful in C++?
13. Class B is inherited from class A. A uses a dynamic pointer. B inherits that
dynamic pointer and uses another dynamic pointer. Write constructor and
destructor for both A and B
14. What is default constructor? Explain a simple C++ program that explains
default constructor 6
15. Compare default Constructor versus default copy Constructor
16. Specify whether constructors can be used in derived classes or not. If so
explain with an example 6
17. Explain Hierarchical Inheritance and Hybrid Inheritance with an example
18. Explain different types constructors
19. What is constructor? Explain parameterized constructors
20. Write a C++ program to sort a given set of strings in ascending order
21. What is destructor? Explain with example
22. Explain about parameterized constructor with an example
23. Create a class FLOAT that contains one float member. Overload all four
arithmetic operators so that they operate on the objects of FLOAT
24. Explain how dynamic initializations of object achieved with an example
25. Explain the various access specifiers with an example
26. Distinguish between different ways of writing constructor functions in C++.
Give examples.
27. Distinguish between member functions in C++ and functions in C –
language.

www.eduwing.blogspot.in
Important Questions

28. Give a class specification for time in hours, minutes and seconds and write a
member function that determines the difference between two times. Assume
that all times are in 24 hour format.

UNIT-IV

1. What does polymorphism mean in C++ language?


2. How is polymorphism achieved at COMPILE TIME and ii) RUN TIME?
3. Explain, with an example, how you could create space for an array of objects
using pointers.
4. What does ‘this’ pointer point to?
5. Discuss the different ways by which we can access public member functions
of an object.
6. What are the applications of ‘this’ pointer?
7. What is a virtual function? Why do we need virtual function?
8. When do we make a virtual function pure? What are the implications of
making a function a pure virtual function?
9. What is the purpose of new operator in C++? What does delete operator do
in C++?
10. What are virtual destructors? How are they used in C++?
11. What is virtual function? When is it needed?
12. Distinguish between abstract classes and pure virtual functions
13. What is the difference between compile time polymorphism and Run time
polymorphism
14. Write a C++ program that illustrates compile time polymorphism
15. What is the primary use of a Virtual Destructors?
16. How the abstract classes are used in pure Virtual functions? Explain it with
an example
17. What is Polymorphism? Explain with example
18. Write a short notes on Memory Management in C++
19. Explain the use of ‘THIS’ pointer in C++. Give examples
20. Explain Pure virtual Functions with examples
21. Explain about the virtual base class with an example
22. Explain about the ambiguity in inheritance with any specific program
example
23. Develop an object oriented programming in C++ to prepare the mark sheet
of an university examination with the following items read from the
keyboard:

www.eduwing.blogspot.in
Important Questions

Name of the student


Roll number
Subject name
Subject code
Internal marks
External marks
24. Design a base class consisting of the data members such as name of the
student, roll number and subject name. The derived class consists of the data
members viz., subject code, internal marks and external marks. The program
must be able to build a table, list a table, insert a new entry and deleting a
new entry
25. What are virtual functions? How do they help in designing O O programs?
26. What are function templates? What are class templates? Give examples.
27. Distinguish between single and multiple inheritance and give examples.
28. Write templated class specification for complex numbers with prototype
definitions for member functions add, subtract and multiply.

UNIT-V

1. What are generic classes? Describe tools available in C++ to define generic
classes. 6
2. Define throw and catch mechanisms in C++. 6
3. Define exception? How are they handled in C++. 6
4. Write a program to read integers and when a non-integer is encountered
throw exception.
5. What are the advantages of using templates in C++ programming
6. Explain the differences between Templates and Macros
7. Write a program to demonstrate the concept of rethrowing an exception
8. Define a class template for a stack
9. What is exception? Explain exception handling with examples
10. Explain function templates with multiple parameters
11. Explain the use of nested class templates
12. Describe the process of throwing parameterized objects of a nested
exception class
13. Explain Function Templates with an example
14. Define Class Templates with an example
15. Write a C++ program that tests Divide by zero and divide by negative
number
16. Describe the limitations of exception handling in C++

www.eduwing.blogspot.in
Important Questions

17. Define a function template that returns the sum of an array of elements. The
function must use two arguments-the type of array (generic) and the size of
array (int)
18. What is generic programming? How is it implemented in C++?
19. Distinguish between overloaded functions and function templates.
20. What are the advantages of using exception handling mechanism in a
program.
21. When should a program throw an exception?
22. A template can be considered as a kind of macro. Explain the difference
between them.
23. Distinguish between the terms class template and template class.
24. What is an exception? How is an exception handled in C++?
25. What is an exception specification? When is it used?

www.eduwing.blogspot.in

Das könnte Ihnen auch gefallen