Object Oriented Programming Using C++ NOTES
Object Oriented Programming Using C++ NOTES
BANGALORE – 560103
1|P age
C++ OVERVIEW
2|P age
#include<iostream>
usingnamespacestd;
int main()
{
cout<<"Hello World";
return0;
}
• Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, eating. An object is an
instance of a class.
• Instance Variables - Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
++ Program Structure:
Let us look at a simple code that would print the words Hello World.
#include<iostream>
usingnamespacestd;
3|P age
int main()
{
cout<<"Hello World";// prints Hello World
return0;
}
• The C++ language defines several headers, which contain information that is
either necessary or useful to your program. For this program, the
header <iostream> is needed.
• The line using namespace std; tells the compiler to use the std namespace.
Namespaces are a relatively recent addition to C++.
• The line intmain() is the main function where program execution begins.
• The next line cout<< "This is my first C++ program."; causes the message
"This is my first C++ program" to be displayed on the screen.
• The next line return 0; terminates main( )function and causes it to return the
value 0 to the calling process.
C++ Identifiers:
A C++ identifier is a name used to identify a variable, function, class,
module, or any other user-defined item. An identifier starts with a letter A
to Z or a to z or an underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).
4|P age
mohdzaraabcmove_name a_123
myname50 _temp j a23b9 retVal
C++ Keywords:
The following list shows the reserved words in C++. These reserved words
may not be used as constant or variable or any other identifier names.
5|P age
delete int static_cast volatile
Comments in C++
Program comments are explanatory statements that you can include in the
C++ code that you write and helps anyone reading it's source code. All
programming languages allow for some form of comments.
C++ comments start with /* and end with */. For example:
/* This is a comment */
A comment can also start with //, extending to the end of the line. For
example:
#include<iostream>
usingnamespacestd;
main()
{
cout<<"Hello World";// prints Hello World
return0;
6|P age
}
When the above code is compiled, it will ignore // prints Hello World and
final executable will produce the following result:
HelloWorld
*/
You may like to store information of various data types like character, wide
character, integer, 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
7|P age
Character char
Integer int
Valueless void
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 value
which can be stored in such type of variables.
8|P age
int 4bytes -2147483648 to 2147483647
The sizes of variables might be different from those shown in the above
table, depending on the compiler and the computer you are using.
Following is the example, which will produce correct size of various data
types on your computer.
#include<iostream>
9|P age
usingnamespacestd;
int main()
{
cout<<"Size of char : "<<sizeof(char)<<endl;
cout<<"Size of int : "<<sizeof(int)<<endl;
cout<<"Size of short int : "<<sizeof(shortint)<<endl;
cout<<"Size of long int : "<<sizeof(longint)<<endl;
cout<<"Size of float : "<<sizeof(float)<<endl;
cout<<"Size of double : "<<sizeof(double)<<endl;
cout<<"Size of wchar_t : "<<sizeof(wchar_t)<<endl;
return0;
}
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() operator to get size of various data types.
When the above code is compiled and executed, it produces the following
result which can vary from machine to machine:
Size of char:1
Size of int:4
Size of shortint:2
Size of longint:8
Size of float:4
Size of double:8
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:
10 | P a g e
For example, the following tells the compiler that feet is another name for
int:
typedefint feet;
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.
Here, the enum-name is the enumeration's type name. The list of names is
comma separated.
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 give 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 greater
than the one that precedes it.
11 | P a g e
C++ Variable Types
Advertisements
Previous Page
Next Page
Type Description
12 | P a g e
void Represents the absence of type.
C++ also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array,
Reference, Data structures, and Classes.
Following section will cover how to define, declare and use various types of
variables.
typevariable_list;
Here, type must be a valid C++ data type including char, w_char, int, float,
double, bool or any user-defined object, etc., and variable_list may
consist of one or more identifier names separated by commas. Some valid
declarations are shown here:
inti, j, k;
char c,ch;
float f, salary;
double d;
The line inti, j, k; both declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j and k of type int.
typevariable_name= value;
13 | P a g e
Some examples are:
A variable declaration is useful when you are using multiple files and you
define your variable in one of the files which will be available at the time of
linking of the program. You will use extern keyword to declare a variable at
any place. Though you can declare a variable multiple times in your C++
program, but it can be defined only once in a file, a function or a block of
code.
Example
Try the following example where a variable has been declared at the top,
but it has been defined inside the main function:
#include<iostream>
usingnamespacestd;
// Variable declaration:
externint a, b;
externint c;
14 | P a g e
externfloat f;
int main ()
{
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a =10;
b =20;
c = a + b;
cout<< c <<endl;
f =70.0/3.0;
cout<< f <<endl;
return0;
}
When the above code is compiled and executed, it produces the following
result:
30
23.3333
// function declaration
intfunc();
15 | P a g e
int main()
{
// function call
inti=func();
}
// function definition
intfunc()
{
return0;
}
C++ Constants/Literals
Advertisements
Previous Page
Next Page
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.
16 | P a g e
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 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
17 | P a g e
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:
You should not consider the value of true equal to 1 and value of false equal
to 0.
Character literals:
Character literals are enclosed in single quotes. If the literal begins with L
(uppercase only), it is a wide character literal (e.g., L'x') and should be
stored inwchar_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.
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:
\\ \ character
18 | P a g e
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
#include<iostream>
usingnamespacestd;
int main()
{
cout<<"Hello\tWorld\n\n";
return0;
}
When the above code is compiled and executed, it produces the following
result:
19 | P a g e
HelloWorld
String literals:
String literals are enclosed in double quotes. A string contains characters
that are similar to character literals: plain characters, escape sequences,
and universal characters.
You can break a long line into multiple lines using string literals and
separate them using whitespaces.
Here are some examples of string literals. All the three forms are identical
strings.
"hello, dear"
"hello, \
dear"
"hello, ""d""ear"
Defining Constants:
There are two simple ways in C++ to define constants:
#include<iostream>
usingnamespacestd;
20 | P a g e
#define LENGTH 10
#defineWIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
When the above code is compiled and executed, it produces the following
result:
50
#include<iostream>
usingnamespacestd;
int main()
{
constint LENGTH =10;
constint WIDTH =5;
21 | P a g e
constchar NEWLINE ='\n';
int area;
When the above code is compiled and executed, it produces the following
result:
50
Advertisements
Previous Page
Next Page
C++ allows the char, int, and double data types to have modifiers
preceding them. A modifier is used to alter the meaning of the base type so
that it more precisely fits the needs of various situations.
• signed
• unsigned
• long
• short
22 | P a g e
The modifiers signed, unsigned, long, and short can be applied to
integer base types. In addition, signed and unsigned can be applied to
char, and longcan be applied to double.
unsigned x;
unsignedint y;
To understand the difference between the way that signed and unsigned
integer modifiers are interpreted by C++, you should run the following
short program:
#include<iostream>
usingnamespacestd;
j =50000;
i= j;
cout<<i<<" "<< j;
return0;
23 | P a g e
}
-1553650000
The above result is because the bit pattern that represents 50,000 as a
short unsigned integer is interpreted as -15,536 by a short.
Qualifier Meaning
volatile The modifier volatile tells the compiler that a variable's value may be
changed in ways not explicitly specified by the program.
restrict A pointer qualified by restrict is initially the only means by which the
object it points to can be accessed. Only C99 adds a new type qualifier
called restrict.
Operators in C++
Advertisements
Previous Page
Next Page
24 | P a g e
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators:
There are following arithmetic operators supported by C++ language:
Show Examples
25 | P a g e
++ Increment operator, increases A++ will give 11
integer value by one
Relational Operators:
There are following relational operators supported by C++ language
Show Examples
26 | P a g e
condition becomes true.
Logical Operators:
There are following logical operators supported by C++ language
Show Examples
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:
27 | P a g e
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following
table. Assume variable A holds 60 and variable B holds 13, then:
Show Examples
& Binary AND Operator copies a bit (A & B) will give 12 which is 0000
to the result if it exists in both 1100
operands.
28 | P a g e
it exists in either operand. 1101
<< Binary Left Shift Operator. The A << 2 will give 240 which is
left operands value is moved left 1111 0000
by the number of bits specified by
the right operand.
>> Binary Right Shift Operator. The A >> 2 will give 15 which is 0000
left operands value is moved right 1111
by the number of bits specified by
the right operand.
Assignment Operators:
There are following assignment operators supported by C++ language:
Show Examples
29 | P a g e
-= Subtract AND assignment C -= A is equivalent to C = C - A
operator, It subtracts right
operand from the left operand
and assign the result to left
operand
Misc Operators
30 | P a g e
There are few other operators supported by C++ Language.
Operator Description
. (dot) and -> (arrow) Member operators are used to reference individual
members of classes, structures, and unions.
31 | P a g e
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator
* has higher precedence than +, so it first gets multiplied with 3*2 and
then adds into 7.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Show Examples
32 | P a g e
Logical AND && Left to right
Advertisements
Previous Page
Next Page
There may be a situation, when you need to execute a block of code several
number of times. In general statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
33 | P a g e
C++ programming language provides the following types of loop to handle
looping requirements. Click the following links to check their detail.
You can use one or more loop inside any another while,
nested loops
for or do..while loop.
34 | P a g e
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
C++ supports the following control statements. Click the following links to
check their detail.
#include<iostream>
usingnamespacestd;
int main ()
{
for(;;)
{
printf("This loop will run forever.\n");
}
35 | P a g e
return0;
}
Advertisements
Previous Page
Next Page
36 | P a g e
C++ programming language provides following types of decision making
statements. Click the following links to check their detail.
Statement Description
37 | P a g e
The ? : Operator:
We have covered conditional operator ? : in previous chapter which can be
used to replace if...else statements. It has the following general form:
Exp1?Exp2:Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and
placement of the colon.
C++ Functions
Advertisements
Previous Page
Next Page
You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the division
usually is so each function performs a specific task.
The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat() to concatenate two
38 | P a g e
strings, function memcpy() to copy one memory location to another
location and many more functions.
Defining a Function:
The general form of a C++ function definition is as follows:
• Return Type: A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
• Function Name: This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
Example:
39 | P a g e
Following is the source code for a function called max(). This function takes
two parameters num1 and num2 and returns the maximum between the
two:
return result;
}
Function Declarations:
A function declaration tells the compiler about a function name and how to
call the function. The actual body of the function can be defined separately.
For the above defined function max(), following is the function declaration:
Parameter names are not importan in function declaration only their type is
required, so following is also valid declaration:
int max(int,int);
40 | P a g e
Function declaration is required when you define a function in one source
file and you call that function in another file. In such case, you should
declare the function at the top of the file calling the function.
Calling a Function:
While creating a C++ function, you give a definition of what the function
has to do. To use a function, you will have to call or invoke that function.
To call a function, you simply need to pass the required parameters along
with function name, and if function returns a value, then you can store
returned value. For example:
#include<iostream>
usingnamespacestd;
// function declaration
int max(int num1,int num2);
int main ()
{
// local variable declaration:
int a =100;
int b =200;
int ret;
41 | P a g e
return0;
}
return result;
}
I kept max() function along with main() function and compiled the source
code. While running final executable, it would produce the following result:
Function Arguments:
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
parameters of the function.
The formal parameters behave like other local variables inside the function
and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed
to a function:
42 | P a g e
This method copies the actual value of an argument into
Call by value
the formal parameter of the function. In this case,
changes made to the parameter inside the function have
no effect on the argument.
This is done by using the assignment operator and assigning values for the
arguments in the function definition. If a value for that parameter is not
passed when the function is called, the default given value is used, but if a
value is specified, this default value is ignored and the passed value is used
instead. Consider the following example:
#include<iostream>
usingnamespacestd;
43 | P a g e
int result;
result= a + b;
return(result);
}
int main ()
{
// local variable declaration:
int a =100;
int b =200;
int result;
return0;
}
When the above code is compiled and executed, it produces the following
result:
C++ Arrays
Advertisements
44 | P a g e
Previous Page
Next Page
Declaring Arrays:
To declare an array in C++, the programmer specifies the type of the
elements and the number of elements required by an array as follows:
typearrayName[arraySize];
double balance[10];
Initializing Arrays:
You can initialize C++ array elements either one by one or using a single
statement as follows:
double balance[5]={1000.0,2.0,3.4,17.0,50.0};
45 | P a g e
The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square brackets
[ ]. Following is an example to assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write:
double balance[]={1000.0,2.0,3.4,17.0,50.0};
You will create exactly the same array as you did in the previous example.
balance[4]=50.0;
The above statement assigns element number 5th in the array a value of
50.0. Array with 4th index will be 5th, i.e., last element because all arrays
have 0 as the index of their first element which is also called base index.
Following is the pictorial representaion of the same array we discussed
above:
The above statement will take 10th element from the array and assign the
value to salary variable. Following is an example, which will use all the
above-mentioned three concepts viz. declaration, assignment and accessing
arrays:
#include<iostream>
usingnamespacestd;
#include<iomanip>
46 | P a g e
usingstd::setw;
int main ()
{
int n[10];// n is an array of 10 integers
return0;
}
This program makes use of setw() function to format the output. When the
above code is compiled and executed, it produces the following result:
ElementValue
0100
1101
2102
3103
4104
5105
6106
7107
47 | P a g e
8108
9109
Concept Description
C++ Strings
Advertisements
Previous Page
Next Page
48 | P a g e
• The string class type introduced with Standard C++.
char greeting[6]={'H','e','l','l','o','\0'};
If you follow the rule of array initialization, then you can write the above
statement as follows:
char greeting[]="Hello";
Actually, you do not place the null character at the end of a string constant.
The C++ compiler automatically places the '\0' at the end of the string
when it initializes the array. Let us try to print above-mentioned string:
#include<iostream>
49 | P a g e
usingnamespacestd;
int main ()
{
char greeting[6]={'H','e','l','l','o','\0'};
return0;
}
Greeting message:Hello
1 strcpy(s1, s2);
2 strcat(s1, s2);
3 strlen(s1);
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
50 | P a g e
s1>s2.
5 strchr(s1, ch);
6 strstr(s1, s2);
#include<iostream>
#include<cstring>
usingnamespacestd;
int main ()
{
char str1[10]="Hello";
char str2[10]="World";
char str3[10];
intlen;
51 | P a g e
cout<<"strlen(str1) : "<<len<<endl;
return0;
}
At this point, you may not understand this example because so far we have
not discussed Classes and Objects. So can have a look and proceed until
you have understanding on Object Oriented Concepts.
#include<iostream>
#include<string>
usingnamespacestd;
int main ()
{
string str1 ="Hello";
string str2 ="World";
string str3;
intlen;
52 | P a g e
str3 = str1;
cout<<"str3 : "<< str3 <<endl;
return0;
}
str3 :Hello
str1 +str2 :HelloWorld
str3.size():10
C++ Pointers
Advertisements
Previous Page
Next Page
C++ pointers are easy and fun to learn. Some C++ tasks are performed
more easily with pointers, and other C++ tasks, such as dynamic memory
allocation, cannot be performed without them.
53 | P a g e
operator which denotes an address in memory. Consider the following which
will print the address of the variables defined:
#include<iostream>
usingnamespacestd;
int main ()
{
int var1;
char var2[10];
return0;
}
Advertisements
Previous Page
Next Page
54 | P a g e
The C++ standard libraries provide an extensive set of input/output
capabilities which we will see in subsequent chapters. This chapter will
discuss very basic and most common I/O operations required for C++
programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow
from a device like a keyboard, a disk drive, or a network connection etc. to
main memory, this is called input operation and if bytes flow from main
memory to a device like a display screen, a printer, a disk drive, or a
network connection, etc, this is called output operation.
<iostream> This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output
stream, the un-buffered standard error stream and the buffered
standard error stream, respectively.
<iomanip> This file declares services useful for performing formatted I/O
with so-called parameterized stream manipulators, such
as setwand setprecision.
#include<iostream>
55 | P a g e
usingnamespacestd;
int main()
{
charstr[]="Hello C++";
When the above code is compiled and executed, it produces the following
result:
The C++ compiler also determines the data type of variable to be output
and selects the appropriate stream insertion operator to display the value.
The << operator is overloaded to output data items of built-in types
integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single
statement as shown above and endl is used to add a new-line at the end of
the line.
#include<iostream>
usingnamespacestd;
int main()
56 | P a g e
{
char name[50];
When the above code is compiled and executed, it will prompt you to enter
a name. You enter a value and then hit enter to see the result something as
follows:
The C++ compiler also determines the data type of the entered value and
selects the appropriate stream extraction operator to extract the value and
store it in the given variables.
The stream extraction operator >> may be used more than once in a single
statement. To request more than one datum you can use the following:
cin>> name;
cin>> age;
57 | P a g e
The cerr is also used in conjunction with the stream insertion operator as
shown in the following example.
#include<iostream>
usingnamespacestd;
int main()
{
charstr[]="Unable to read....";
When the above code is compiled and executed, it produces the following
result:
Advertisements
Previous Page
Next Page
58 | P a g e
C++ Class Definitions:
When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means,
that is, what an object of the class will consist of and what operations can
be performed on such an object.
A class definition starts with the keyword class followed by the class name;
and the class body, enclosed by a pair of curly braces. A class definition
must be followed either by a semicolon or a list of declarations. For
example, we defined the Box data type using the keyword class as follows:
classBox
{
public:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box
};
Both of the objects Box1 and Box2 will have their own copy of data
members.
59 | P a g e
Accessing the Data Members:
The public data members of objects of a class can be accessed using the
direct member access operator (.). Let us try the following example to
make the things clear:
#include<iostream>
usingnamespacestd;
classBox
{
public:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box
};
int main()
{
BoxBox1;// Declare Box1 of type Box
BoxBox2;// Declare Box2 of type Box
double volume =0.0;// Store the volume of a box here
// box 1 specification
Box1.height =5.0;
Box1.length =6.0;
Box1.breadth =7.0;
// box 2 specification
Box2.height =10.0;
Box2.length =12.0;
Box2.breadth =13.0;
// volume of box 1
60 | P a g e
volume=Box1.height *Box1.length *Box1.breadth;
cout<<"Volume of Box1 : "<< volume <<endl;
// volume of box 2
volume=Box2.height *Box2.length *Box2.breadth;
cout<<"Volume of Box2 : "<< volume <<endl;
return0;
}
When the above code is compiled and executed, it produces the following
result:
Volume of Box1:210
Volume of Box2:1560
Concept Description
61 | P a g e
function which is called when created object is
deleted.
C++ Inheritance
Advertisements
Previous Page
Next Page
62 | P a g e
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called
the baseclass, and the new class is referred to as the derived class.
Consider a base class Shape and its derived class Rectangle as follows:
#include<iostream>
usingnamespacestd;
// Base class
classShape
{
public:
voidsetWidth(int w)
{
width= w;
}
voidsetHeight(int h)
63 | P a g e
{
height= h;
}
protected:
int width;
int height;
};
// Derived class
classRectangle:publicShape
{
public:
intgetArea()
{
return(width * height);
}
};
int main(void)
{
RectangleRect;
Rect.setWidth(5);
Rect.setHeight(7);
return0;
}
When the above code is compiled and executed, it produces the following
result:
64 | P a g e
Total area:35
We can summarize the different access types according to who can access
them in the following way:
A derived class inherits all base class methods with the following
exceptions:
Type of Inheritance:
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance
is specified by the access-specifier as explained above.
65 | P a g e
• Public Inheritance: When deriving a class from a public base
class,public members of the base class become public members of the derived
class and protected members of the base class becomeprotected members of
the derived class. A base class's privatemembers are never accessible directly
from a derived class, but can be accessed through calls to
the public and protected members of the base class.
Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the
extended syntax:
#include<iostream>
usingnamespacestd;
66 | P a g e
}
voidsetHeight(int h)
{
height= h;
}
protected:
int width;
int height;
};
// Derived class
classRectangle:publicShape,publicPaintCost
{
public:
intgetArea()
{
return(width * height);
}
};
int main(void)
{
RectangleRect;
67 | P a g e
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area=Rect.getArea();
return0;
}
When the above code is compiled and executed, it produces the following
result:
Total area:35
Total paint cost: $2450
Advertisements
Previous Page
Next Page
C++ allows you to specify more than one definition for a function name or
anoperator in the same scope, which is called function
overloading andoperator overloading respectively.
68 | P a g e
An overloaded declaration is a declaration that had been declared with the
same name as a previously declared declaration in the same scope, except
that both declarations have different arguments and obviously different
definition (implementation).
Following is the example where same function print() is being used to print
different data types:
#include<iostream>
usingnamespacestd;
classprintData
{
public:
voidprint(inti){
cout<<"Printing int: "<<i<<endl;
}
voidprint(double f){
cout<<"Printing float: "<< f <<endl;
}
69 | P a g e
voidprint(char* c){
cout<<"Printing character: "<< c <<endl;
}
};
int main(void)
{
printDatapd;
return0;
}
When the above code is compiled and executed, it produces the following
result:
Printingint:5
Printingfloat:500.263
Printing character:Hello C++
70 | P a g e
Boxoperator+(constBox&);
declares the addition operator that can be used to add two Box objects and
returns final Box object. Most overloaded operators may be defined as
ordinary non-member functions or as class member functions. In case we
define above function as non-member function of a class then we would
have to pass two arguments for each operand as follows:
Boxoperator+(constBox&,constBox&);
Following is the example to show the concept of operator over loading using
a member function. Here an object is passed as an argument whose
properties will be accessed using this object, the object which will call this
operator can be accessed using this operator as explained below:
#include<iostream>
usingnamespacestd;
classBox
{
public:
doublegetVolume(void)
{
return length * breadth * height;
}
voidsetLength(doublelen)
{
length=len;
}
voidsetBreadth(doublebre)
{
breadth=bre;
}
71 | P a g e
voidsetHeight(doublehei)
{
height=hei;
}
// Overload + operator to add two Box objects.
Boxoperator+(constBox& b)
{
Boxbox;
box.length=this->length +b.length;
box.breadth=this->breadth +b.breadth;
box.height=this->height +b.height;
return box;
}
private:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box
};
// Main function for the program
int main()
{
BoxBox1;// Declare Box1 of type Box
BoxBox2;// Declare Box2 of type Box
BoxBox3;// Declare Box3 of type Box
double volume =0.0;// Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
72 | P a g e
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;
// volume of box 3
volume=Box3.getVolume();
cout<<"Volume of Box3 : "<< volume <<endl;
return0;
}
When the above code is compiled and executed, it produces the following
result:
Volume of Box1:210
Volume of Box2:1560
Volume of Box3:5400
Overloadable/Non-overloadableOperators:
Following is the list of operators which can be overloaded:
+ - * / % ^
73 | P a g e
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
:: .* . ?:
1
Unary operators overloading
2
Binary operators overloading
3
Relational operators overloading
4
Input/Output operators overloading
74 | P a g e
5
++ and -- operators overloading
6
Assignment operators overloading
7
Function call () operator overloading
8
Subscripting [] operator overloading
9
Class member access operator -> overloading
Polymorphism in C++
Advertisements
Previous Page
Next Page
Consider the following example where a base class has been derived by
other two classes:
#include<iostream>
usingnamespacestd;
classShape{
protected:
75 | P a g e
int width, height;
public:
Shape(int a=0,int b=0)
{
width= a;
height= b;
}
int area()
{
cout<<"Parent class area :"<<endl;
return0;
}
};
classRectangle:publicShape{
public:
Rectangle(int a=0,int b=0):Shape(a, b){}
int area ()
{
cout<<"Rectangle class area :"<<endl;
return(width * height);
}
};
classTriangle:publicShape{
public:
Triangle(int a=0,int b=0):Shape(a, b){}
int area ()
{
cout<<"Triangle class area :"<<endl;
return(width * height /2);
}
};
// Main function for the program
int main()
76 | P a g e
{
Shape*shape;
Rectanglerec(10,7);
Triangle tri(10,5);
return0;
}
When the above code is compiled and executed, it produces the following
result:
Parentclass area
Parentclass area
The reason for the incorrect output is that the call of the function area() is
being set once by the compiler as the version defined in the base class. This
is calledstatic resolution of the function call, or static linkage - the
function call is fixed before the program is executed. This is also sometimes
called early binding because the area() function is set during the
compilation of the program.
But now, let's make a slight modification in our program and precede the
declaration of area() in the Shape class with the keyword virtual so that it
looks like this:
classShape{
77 | P a g e
protected:
int width, height;
public:
Shape(int a=0,int b=0)
{
width= a;
height= b;
}
virtualint area()
{
cout<<"Parent class area :"<<endl;
return0;
}
};
After this slight modification, when the previous example code is compiled
and executed, it produces the following result:
Rectangleclass area
Triangleclass area
This time, the compiler looks at the contents of the pointer instead of it's
type. Hence, since addresses of objects of tri and rec classes are stored in
*shape the respective area() function is called.
As you can see, each of the child classes has a separate implementation for
the function area(). This is how polymorphism is generally used. You have
different classes with a function of the same name, and even the same
parameters, but with different implementations.
Virtual Function:
A virtual function is a function in a base class that is declared using the
keyword virtual. Defining in a base class a virtual function, with another
version in a derived class, signals to the compiler that we don't want static
linkage for this function.
78 | P a g e
What we do want is the selection of the function to be called at any given
point in the program to be based on the kind of object for which it is called.
This sort of operation is referred to as dynamic linkage, or late binding.
We can change the virtual function area() in the base class to the following:
classShape{
protected:
int width, height;
public:
Shape(int a=0,int b=0)
{
width= a;
height= b;
}
// pure virtual function
virtualint area()=0;
};
The = 0 tells the compiler that the function has no body and above virtual
function will be called pure virtual function.
Advertisements
Previous Page
Next Page
79 | P a g e
So far, we have been using the iostream standard library, which
provides cinand cout methods for reading from standard input and writing
to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires
another standard C++ library called fstream, which defines three new data
types:
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 generally, and
has the capabilities of both ofstream and ifstream which
means it can create files, write information to files, and
read information from files.
Opening a File:
A file must be opened before you can read from it or write to it. Either
theofstream or fstream object may be used to open a file for writing
andifstream object is used to open a file for reading purpose only.
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.
80 | P a g e
Mode Flag Description
ios::ate Open a file for output and move the read/write control to
the end of the file.
You can combine two or more of these values by ORing them together. For
example if you want to open a file in write mode and want to truncate it in
case it already exists, following will be the syntax:
ofstreamoutfile;
outfile.open("file.dat",ios::out|ios::trunc);
Similar way, you can open a file for reading and writing purpose as follows:
fstreamafile;
afile.open("file.dat",ios::out|ios::in);
Closing a File
When a C++ program terminates it automatically closes flushes all the
streams, release all the allocated memory and close all the opened files. But
it is always a good practice that a programmer should close all the opened
files before program termination.
81 | P a g e
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your
program using the stream insertion operator (<<) just as you use that
operator to output information to the screen. The only difference is that you
use anofstream or fstream object instead of the cout object.
#include<fstream>
#include<iostream>
usingnamespacestd;
int main ()
{
char data[100];
82 | P a g e
cout<<"Enter your name: ";
cin.getline(data,100);
// again read the data from the file and display it.
infile>> data;
cout<< data <<endl;
83 | P a g e
return0;
}
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
Readingfrom the file
Zara
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.
The file-position pointer is an integer value that specifies the location in the
file as a number of bytes from the file's starting location. Some examples of
positioning the "get" file-position pointer are:
84 | P a g e
fileObject.seekg( n,ios::cur );
Advertisements
Previous Page
Next Page
• throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.
• try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
try
{
// protected code
}catch(ExceptionName e1 )
{
// catch block
}catch(ExceptionName e2 )
{
// catch block
}catch(ExceptionNameeN)
{
// catch block
}
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.
Throwing Exceptions:
Exceptions can be thrown anywhere within a code block
using throwstatements. The operand of the throw statements determines a
type for the exception and can be any expression and the type of the result
of the expression determines the type of exception thrown.
86 | P a g e
}
return(a/b);
}
Catching Exceptions:
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined by
the exception declaration that appears in parentheses following the keyword
catch.
try
{
// protected code
}catch(ExceptionName e )
{
// code to handle ExceptionName exception
}
try
{
// protected code
}catch(...)
{
// code to handle any exception
}
#include<iostream>
usingnamespacestd;
87 | P a g e
double division(int a,int b)
{
if( b ==0)
{
throw"Division by zero condition!";
}
return(a/b);
}
int main ()
{
int x =50;
int y =0;
double z =0;
try{
z = division(x, y);
cout<< z <<endl;
}catch(constchar*msg){
cerr<<msg<<endl;
}
return0;
}
88 | P a g e
C++ provides a list of standard exceptions defined in <exception> which
we can use in our programs. These are arranged in a parent-child class
hierarchy shown below:
Exception Description
89 | P a g e
std::bad_cast This can be thrown by dynamic_cast.
std::range_error This is occured when you try to store a value which is out
of range.
#include<iostream>
#include<exception>
usingnamespacestd;
structMyException:public exception
{
constchar* what ()constthrow()
{
return"C++ Exception";
}
};
int main()
{
try
{
throwMyException();
}
catch(MyException& e)
{
std::cout<<"MyException caught"<<std::endl;
std::cout<<e.what()<<std::endl;
}
catch(std::exception& e)
{
//Other errors
}
}
91 | P a g e
MyException caught
C++Exception
C++ Templates
Advertisements
Previous Page
Next Page
You can use templates to define functions as well as classes, let us see how
do they work:
Function Template:
The general form of a template function definition is shown here:
92 | P a g e
Here, type is a placeholder name for a data type used by the function. This
name can be used within the function definition.
#include<iostream>
#include<string>
usingnamespacestd;
template<typename T>
inline T const&Max(T const& a, T const& b)
{
return a < b ?b:a;
}
int main ()
{
inti=39;
int j =20;
cout<<"Max(i, j): "<<Max(i, j)<<endl;
double f1 =13.5;
double f2 =20.7;
cout<<"Max(f1, f2): "<<Max(f1, f2)<<endl;
string s1 ="Hello";
string s2 ="World";
cout<<"Max(s1, s2): "<<Max(s1, s2)<<endl;
return0;
}
93 | P a g e
If we compile and run above code, this would produce the following result:
Max(i, j):39
Max(f1, f2):20.7
Max(s1, s2):World
Class Template:
Just as we can define function templates, we can also define class
templates. The general form of a generic class declaration is shown here:
template<class type>classclass-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a
class is instantiated. You can define more than one generic data type by
using a comma-separated list.
#include<iostream>
#include<vector>
#include<cstdlib>
#include<string>
#include<stdexcept>
usingnamespacestd;
template<class T>
classStack{
private:
vector<T>elems;// elements
94 | P a g e
public:
void push(T const&);// push element
void pop();// pop element
T top()const;// return top element
bool empty()const{// return true if empty.
returnelems.empty();
}
};
template<class T>
voidStack<T>::push (T const&elem)
{
// append copy of passed element
elems.push_back(elem);
}
template<class T>
voidStack<T>::pop ()
{
if(elems.empty()){
throwout_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
template<class T>
T Stack<T>::top()const
{
if(elems.empty()){
throwout_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
95 | P a g e
returnelems.back();
}
int main()
{
try{
Stack<int>intStack;// stack of ints
Stack<string>stringStack;// stack of strings
If we compile and run above code, this would produce the following result:
7
hello
Exception:Stack<>::pop(): empty stack
96 | P a g e