Beruflich Dokumente
Kultur Dokumente
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.
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.
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.
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++.
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;
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:
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 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
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
Include files
Class declaration
Member functions
definitions
Main function program
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>
8 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1
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:
There are another 30 reserved words that were not in C, are therefore new to C++, and here they
are:
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
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.
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
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.
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:
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:
11 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1
#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"
Defining Constants:
There are two simple ways in C++ to define constants:
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;
When the above code is compiled and executed, it produces the following result:
50
#include <iostream>
using namespace std;
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
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
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.
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.
14 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1
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:
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:
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".
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.
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.
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:
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.
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
20 www.eduwing.blogspot.in by M. A. Srinuvasu
Object Oriented Programming with C++ Unit -1
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.
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
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:
Example:
int *p; //declaration of a pointer variable
p=new int; //allocate two bytes of memory for p
*p=25;
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
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.
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.
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
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:
Example:
#include <iostream>
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
// 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:
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 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:
ADDRESS:
2 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
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:
#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
4 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
Like static member variable, we can also have static member function.
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;
#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
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;
}
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
Example:
#inlude<iostream.h>
class Time
int hours;
int minutes;
public:
hours = h;
minutes = m;
void puttime ( )
cout<<hours<<”hours and”;
cout<<minutes<<”minutes”<<endl;
};
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
hours = minutes/60;
int main( )
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 ;
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
public:
x = real ;
y = img ;
};
c3.y = c1.y+c2.y;
int main( )
11 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
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
# 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;
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:
Example:
The const modifier assigns an initial value to a variable that cannot be changed later by program.
14 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
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.
inline function_header
function body
Some of the situations where inline expansion may not work are:
15 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
#include<iostream.h>
return ( x * y);
return ( p / q);
int main( )
float c=8.45,d=5.35;
return 0;
Output:
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
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:
The functions return type may be similar (or) void, but it must be different in number of
arguments or arguments data types.
Example1:
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:
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.
#include<iostream.h>
17 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
#include<conio.h>
return x+y ;
return x+y;
return x+y;
return x+y;
int main( )
int a , b;
float c , d;
18 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
cin>> a >> b;
cin>> c >> d;
cout<< add ( a , b );
cout<< add( a , c );
return 0;
Output:
#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:
i = x*x;
return i ;
f = y*y;
return f ;
}; //end of class
int main( )
clrscr( );
int a=5;
float b=2.5;
20 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
return 0;
} //end of main()
Output:
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;
21 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
};
#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>
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
};
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
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.
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:
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:
26 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-II
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:
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
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.
T o remove the array that we have just created the statement would look like this:
Following the similar g eneric syntax of new operator, you can allocat for a multi-dimensional
array as follows:
However, the syntax to release the memory for multi-dimensional array will still remain same as
above:
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) { }
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();
2 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III
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.
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 :
Name = ABC
Rollno =A101
Name = xyz
Rollno =A102
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.
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
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.
program:
#include <iostream>
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
6 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
display(line);
return 0;
}
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.
#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
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 }
Program:
#include <iostream>
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;
};
return 0;
Result:
10 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III
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
11 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III
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();
}
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.
#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:
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
#include<iostream>
17 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:
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
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.
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.
#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
#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
Output:
Hybrid Inheritance
25 www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-III
B C
One may, very well observe that this is a combination of multilevel and multiple 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+
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.
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
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.
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:
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
x.getdata(100,75,50); ptrgetdata(100,75.50)
OR
x.show( ); ptrshow( );
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:
Members of Base
Members +
Members of Derived
/*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;
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.
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
- 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.
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.
- 13 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
++ Increment Unary
Decrement 1
–– Unary
~ complement Unary
, Comma Binary
!= Inequality Binary
% Modulus Binary
* Multiplication Binary
- 14 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
+ Addition Binary
– Subtraction Binary
/ Division Binary
= Assignment Binary
== Equality Binary
- 15 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
^ Exclusive OR 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;
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);
++a;
b++;
- 17 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
b.display();
c = ++a;
d = b++;
--e;
f--;
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;
Inc(int C) {
// Constructor with Argument
count = C ;
}
Inc operator ++ () {
// Operator Function Definition
// for prefix
return Inc(++count);
}
- 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);
}
void display(void) {
cout << count << endl ;
}
};
int main() {
Inc a, b(4), c, d, e(1), f(4);
++a;
b++;
- 20 - www.eduwing.blogspot.in by M.A.Srinuvasu
Object Oriented Programming with C++ UNIT-IV
c = ++a;
d = b++;
--e;
f--;
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);
}
- 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);
}
int main() {
Rational obj1(1,4), obj2(210,840), result1;
result1 = obj1.add(obj2);
result1.show();
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
- 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 );
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.
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 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
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).
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
- 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
- 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();
};
- 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
www.eduwing.blogspot.in
Important Questions
UNIT-II
www.eduwing.blogspot.in
Important Questions
UNIT-III
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
www.eduwing.blogspot.in
Important Questions
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