Vous êtes sur la page 1sur 96

NEW HORIZON COLLEGE, MARATHALLI

BANGALORE – 560103

Subject Code: BCA 303T

Subject Name: Object Oriented Programming Using C++

Name of the Faculty: NagarajuKilari, Sr. Asst.Prof&HOD-BCA

1|P age
C++ OVERVIEW

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-


form programming language that supports procedural, object-oriented, and
generic programming.

C++ is regarded as a middle-level language, as it comprises a


combination of both high-level and low-level language features.

C++ was developed by BjarneStroustrup starting in 1979 at Bell Labs in


Murray Hill, New Jersey, as an enhancement to the C language and
originally named C with Classes but later it was renamed C++ in 1983.

C++ is a superset of C, and that virtually any legal C program is a legal


C++ program.

2|P age
#include<iostream>
usingnamespacestd;

int main()
{
cout<<"Hello World";
return0;
}

When we consider a C++ program, it can be defined as a collection of


objects that communicate via invoking each other's methods. Let us now
briefly look into what do class, object, methods and Instance variables
mean.

• 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.

• Class - A class can be defined as a template/blueprint that describes the


behaviors/states that object of its type support.

• Methods - A method is basically a behavior. A class can contain many methods.


It is in methods where the logics are written, data is manipulated and all the
actions are executed.

• 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;

// main() is where program execution begins.

3|P age
int main()
{
cout<<"Hello World";// prints Hello World
return0;
}

Let us look various parts of the above program:

• 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 next line // main() is where program execution begins. is a single-line


comment available in C++. Single-line comments begin with // and stop at the
end of the line.

• 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).

C++ does not allow punctuation characters such as @, $, and % within


identifiers. C++ is a case-sensitive programming language.
Thus, Manpowerand manpower are two different identifiers in C++.

Here are some examples of acceptable identifiers:

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.

asm else new this

auto enum operator throw

bool explicit private true

break export protected try

case extern public typedef

catch false register typeid

char float reinterpret_cast typename

class for return union

const friend short unsigned

const_cast goto signed using

continue if sizeof virtual

default inline static void

5|P age
delete int static_cast volatile

do long struct wchar_t

double mutable switch while

dynamic_cast namespace template

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++ supports single-line and multi-line comments. All characters available


inside any comment are ignored by C++ compiler.

C++ comments start with /* and end with */. For example:

/* This is a comment */

/* C++ comments can also


* span multiple lines
*/

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

Within a /* and */ comment, // characters have no special meaning. Within


a // comment, /* and */ have no special meaning. Thus, you can "nest" one
kind of comment within the other kind. For example:

/* Comment out printing of Hello World:

cout<< "Hello World"; // prints Hello World

*/

C++ Data Types


While doing programming in any programming language, you need to use
various variables to store various information. 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, 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.

Primitive Built-in Types:


C++ offer the programmer a rich assortment of built-in as well as user
defined data types. Following table lists down seven basic C++ data types:

Type Keyword

Boolean bool

7|P age
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:

• 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.

Type Typical Bit Width Typical Range

char 1byte -128 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -128 to 127

8|P age
int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 4bytes -2,147,483,648 to 2,147,483,647

signed long int 4bytes -2,147,483,648 to 2,147,483,647

unsigned long int 4bytes 0 to 4,294,967,295

float 4bytes +/- 3.4e +/- 38 (~7 digits)

double 8bytes +/- 1.7e +/- 308 (~15 digits)

long double 8bytes +/- 1.7e +/- 308 (~15 digits)

wchar_t 2 or 4 bytes 1 wide character

The sizes of variables might be different from those shown in the above
table, depending on the compiler and the computer you are using.

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

#include<iostream>

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:

typedef type newname;

10 | P a g e
For example, the following tells the compiler that feet is another name for
int:

typedefint feet;

Now, the following declaration is perfectly legal and creates an integer


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


general form of an enumeration type is:

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

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

For example, the following code defines an enumeration of colors called


colors and the variable c of type color. Finally, c is assigned the value
"blue".

enum color { red, green, blue } c;


c = blue;

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

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

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

11 | P a g e
C++ Variable Types

Advertisements

Previous Page
Next Page

A variable provides us with named storage that our programs can


manipulate. Each variable in C++ has a specific type, which determines the
size and layout of the variable's memory; the range of values that can be
stored within that memory; and the set of operations that can be applied to
the variable.

The name of a variable can be composed of letters, digits, and the


underscore character. It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C++ is case-sensitive:

There are following basic types of variable in C++ as explained in last


chapter:

Type Description

bool Stores either value true or false.

char Typically a single octet(one byte). This is an integer


type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

12 | P a g e
void Represents the absence of type.

wchar_t A wide character 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.

Variable Definition in C++:


A variable definition means to tell the compiler where and how much to
create the storage for the variable. A variable definition specifies a data
type, and contains a list of one or more variables of that type as follows:

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.

Variables can be initialized (assigned an initial value) in their declaration.


The initializer consists of an equal sign followed by a constant expression as
follows:

typevariable_name= value;

13 | P a g e
Some examples are:

externint d =3, f =5;// declaration of d and f.


int d =3, f =5;// definition and initializing d and f.
byte z =22;// definition and initializes z.
char x ='x';// the variable x has the value 'x'.

For definition without an initializer: variables with static storage duration


are implicitly initialized with NULL (all bytes have the value 0); the initial
value of all other variables is undefined.

Variable Declaration in C++:


A variable declaration provides assurance to the compiler that there is one
variable existing with the given type and name so that compiler proceed for
further compilation without needing complete detail about the variable. A
variable declaration has its meaning at the time of compilation only,
compiler needs actual variable definition at the time of linking of the
program.

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

Same concept applies on function declaration where you provide a function


name at the time of its declaration and its actual definition can be given
anywhere else. For example:

// 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.

Here are some examples of integer literals:

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

Following are other examples of various types of Integer literals:

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

Floating-point literals:
A floating-point literal has an integer part, a decimal point, a fractional part,
and an exponent part. You can represent floating point literals either in
decimal form or exponential form.

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

Here are some examples of floating-point literals:

3.14159// Legal
314159E-5L// Legal
510E// Illegal: incomplete exponent

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:

• A value of true representing true.

• A value of false representing false.

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

Character literals:
Character literals are enclosed in single quotes. If the literal begins with L
(uppercase only), it is a wide character literal (e.g., L'x') and should be
stored 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.

A character literal can be a plain character (e.g., 'x'), an escape sequence


(e.g., '\t'), or a universal character (e.g., '\u02C0').

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

Escape sequence Meaning

\\ \ character

\' ' character

\" " character

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

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

Following is the example to show few escape sequence characters:

#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:

• Using #define preprocessor.

• Using const keyword.

The #define Preprocessor:


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

#define identifier value

Following example explains it in detail:

#include<iostream>
usingnamespacestd;

20 | P a g e
#define LENGTH 10
#defineWIDTH 5
#define NEWLINE '\n'

int main()
{

int area;

area= LENGTH * WIDTH;


cout<< area;
cout<< NEWLINE;
return0;
}

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

50

The const Keyword:


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

const type variable = value;

Following example explains it in detail:

#include<iostream>
usingnamespacestd;

int main()
{
constint LENGTH =10;
constint WIDTH =5;

21 | P a g e
constchar NEWLINE ='\n';
int area;

area= LENGTH * WIDTH;


cout<< area;
cout<< NEWLINE;
return0;
}

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

50

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


CAPITALS.

C++ Modifier Types

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.

The data type modifiers are listed here:

• 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.

The modifiers signed and unsigned can also be used as prefix


to long orshort modifiers. For example, unsigned long int.

C++ allows a shorthand notation for declaring unsigned,


short, or longintegers. You can simply use the word unsigned,
short, or long, without the int. The int is implied. For example, the
following two statements both declare unsigned integer variables.

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;

/* This program shows the difference between


* signed and unsigned integers.
*/
int main()
{
shortinti;// a signed short integer
shortunsignedint j;// an unsigned short integer

j =50000;

i= j;
cout<<i<<" "<< j;

return0;

23 | P a g e
}

When this program is run, following is the output:

-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.

Type Qualifiers in C++


The type qualifiers provide additional information about the variables they
precede.

Qualifier Meaning

const Objects of type const cannot be changed by your program during


execution

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

An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations. C++ is rich in built-in operators and
provides the following types of operators:

24 | P a g e
• Arithmetic Operators

• Relational Operators

• Logical Operators

• Bitwise Operators

• Assignment Operators

• Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise,


assignment and other operators one by one.

Arithmetic Operators:
There are following arithmetic operators supported by C++ language:

Assume variable A holds 10 and variable B holds 20, then:

Show Examples

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from A - B will give -10


the first

* Multiplies both operands A * B will give 200

/ Divides numerator by de- B / A will give 2


numerator

% Modulus Operator and remainder B % A will give 0


of after an integer division

25 | P a g e
++ Increment operator, increases A++ will give 11
integer value by one

-- Decrement operator, decreases A-- will give 9


integer value by one

Relational Operators:
There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then:

Show Examples

Operator Description Example

== Checks if the values of two (A == B) is not true.


operands are equal or not, if yes
then condition becomes true.

!= Checks if the values of two (A != B) is true.


operands are equal or not, if
values are not equal then
condition becomes true.

> Checks if the value of left operand (A > B) is not true.


is greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand (A < B) is true.


is less than the value of right
operand, if yes then condition
becomes true.

>= Checks if the value of left operand (A >= B) is not true.


is greater than or equal to the
value of right operand, if yes then

26 | P a g e
condition becomes true.

<= Checks if the value of left operand (A <= B) is true.


is less than or equal to the value
of right operand, if yes then
condition becomes true.

Logical Operators:
There are following logical operators supported by C++ language

Assume variable A holds 1 and variable B holds 0, then:

Show Examples

Operator Description Example

&& Called Logical AND operator. If (A && B) is false.


both the operands are non-zero,
then condition becomes true.

|| Called Logical OR Operator. If any (A || B) is true.


of the two operands is non-zero,
then condition becomes true.

! Called Logical NOT Operator. Use !(A && B) is true.


to reverses the logical state of its
operand. If a condition is true,
then Logical NOT operator will
make false.

Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows:

p q p&q p|q p^q

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&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~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

Operator Description Example

& Binary AND Operator copies a bit (A & B) will give 12 which is 0000
to the result if it exists in both 1100
operands.

| Binary OR Operator copies a bit if (A | B) will give 61 which is 0011

28 | P a g e
it exists in either operand. 1101

^ Binary XOR Operator copies the (A ^ B) will give 49 which is 0011


bit if it is set in one operand but 0001
not both.

~ Binary Ones Complement (~A ) will give -61 which is 1100


Operator is unary and has the 0011 in 2's complement form due
effect of 'flipping' bits. to a signed binary number.

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

Operator Description Example

= Simple assignment operator, C = A + B will assign value of A +


Assigns values from right side B into C
operands to left side operand

+= Add AND assignment operator, It C += A is equivalent to C = C + A


adds right operand to the left
operand and assign the result to
left operand

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

*= Multiply AND assignment C *= A is equivalent to C = C * A


operator, It multiplies right
operand with the left operand and
assign the result to left operand

/= Divide AND assignment operator, C /= A is equivalent to C = C / A


It divides left operand with the
right operand and assign the
result to left operand

%= Modulus AND assignment C %= A is equivalent to C = C %


operator, It takes modulus using A
two operands and assign the
result to left operand

<<= Left shift AND assignment C <<= 2 is same as C = C << 2


operator

>>= Right shift AND assignment C >>= 2 is same as C = C >> 2


operator

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and C ^= 2 is same as C = C ^ 2


assignment operator

|= bitwise inclusive OR and C |= 2 is same as C = C | 2


assignment operator

Misc Operators
30 | P a g e
There are few other operators supported by C++ Language.

Operator Description

sizeof sizeof operator returns the size of a variable. For


example, sizeof(a), where a is integer, will return 4.

Condition ? X : Y Conditional operator. If Condition is true ? then it


returns value X : otherwise value Y

, Comma operator causes a sequence of operations to be


performed. The value of the entire comma expression is
the value of the last expression of the comma-separated
list.

. (dot) and -> (arrow) Member operators are used to reference individual
members of classes, structures, and unions.

Cast Casting operators convert one data type to another.


For example, int(2.2000) would return 2.

& Pointer operator & returns the address of an variable.


For example &a; will give actual address of the variable.

* Pointer operator * is pointer to a variable. For example


*var; will pointer to a variable var.

Operators Precedence in C++:


Operator precedence determines the grouping of terms in an expression.
This affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator:

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

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* &sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

32 | P a g e
Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C++ Loop Types

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.

Programming languages provide various control structures that allow for


more complicated execution paths.

A loop statement allows us to execute a statement or group of statements


multiple times and following is the general from of a loop statement in most
of the programming languages:

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.

Loop Type Description

Repeats a statement or group of statements while a


while loop
given condition is true. It tests the condition before
executing the loop body.

Execute a sequence of statements multiple times and


for loop
abbreviates the code that manages the loop variable.

Like a while statement, except that it tests the condition


do...while loop
at the end of the loop body

You can use one or more loop inside any another while,
nested loops
for or do..while loop.

Loop Control Statements:

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.

Control Statement Description

Terminates the loop or switch statement and transfers


break statement
execution to the statement immediately following the
loop or switch.

Causes the loop to skip the remainder of its body and


continue statement
immediately retest its condition prior to reiterating.

Transfers control to the labeled statement. Though it is


goto statement
not advised to use goto statement in your program.

The Infinite Loop:


A loop becomes infinite loop if a condition never becomes false.
The for loop is traditionally used for this purpose. Since none of the three
expressions that form the for loop are required, you can make an endless
loop by leaving the conditional expression empty.

#include<iostream>
usingnamespacestd;

int main ()
{

for(;;)
{
printf("This loop will run forever.\n");
}

35 | P a g e
return0;
}

When the conditional expression is absent, it is assumed to be true. You


may have an initialization and increment expression, but C++ programmers
more commonly use the for(;;) construct to signify an infinite loop.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

C++ decision making statements

Advertisements

Previous Page
Next Page

Decision making structures require that the programmer specify one or


more conditions to be evaluated or tested by the program, along with a
statement or statements to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is
determined to be false.

Following is the general form of a typical decision making structure found in


most of the programming languages:

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

An if statement consists of a boolean expression


if statement
followed by one or more statements.

An if statement can be followed by an optional else


if...else statement
statement, which executes when the boolean
expression is false.

A switch statement allows a variable to be tested for


switch statement
equality against a list of values.

You can use one if or else if statement inside another


nested if statements
if or else if statement(s).

You can use one swicth statement inside another


nested switch
switch statement(s).
statements

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.

The value of a ?expression is determined like this: Exp1 is evaluated. If it is


true, then Exp2 is evaluated and becomes the value of the entire
?expression. If Exp1 is false, then Exp3 is evaluated and its value becomes
the value of the expression.

C++ Functions

Advertisements

Previous Page
Next Page

A function is a group of statements that together perform a task. Every


C++ program has at least one function, which is main(), and all the most
trivial programs can define additional functions.

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.

A function declaration tells the compiler about a function's name, return


type, and parameters. A function definition provides the actual body of the
function.

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.

A function is knows as with various names like a method or a sub-routine or


a procedure etc.

Defining a Function:
The general form of a C++ function definition is as follows:

return_typefunction_name( parameter list )


{
body of the function
}

A C++ function definition consists of a function header and a function body.


Here are all the parts of a function:

• 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.

• Parameters: A parameter is like a placeholder. When a function is invoked, you


pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
contain no parameters.

• Function Body: The function body contains a collection of statements that


define what the function does.

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:

// function returning the max between two numbers

int max(int num1,int num2)


{
// local variable declaration
int result;

if(num1 > num2)


result= num1;
else
result= num2;

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.

A function declaration has the following parts:

return_typefunction_name( parameter list );

For the above defined function max(), following is the function declaration:

int max(int num1,int num2);

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.

When a program calls a function, program control is transferred to the


called function. A called function performs defined task and when its return
statement is executed or when its function-ending closing brace is reached,
it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along
with function name, and if function returns a value, then you can store
returned value. For example:

#include<iostream>
usingnamespacestd;

// function declaration
int max(int num1,int num2);

int main ()
{
// local variable declaration:
int a =100;
int b =200;
int ret;

// calling a function to get max value.


ret= max(a, b);

cout<<"Max value is : "<< ret <<endl;

41 | P a g e
return0;
}

// function returning the max between two numbers


int max(int num1,int num2)
{
// local variable declaration
int result;

if(num1 > num2)


result= num1;
else
result= num2;

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:

Max value is:200

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:

Call Type Description

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 method copies the address of an argument into the


Call by pointer
formal parameter. Inside the function, the address is
used to access the actual argument used in the call. This
means that changes made to the parameter affect the
argument.

This method copies the reference of an argument into


Call by reference
the formal parameter. Inside the function, the reference
is used to access the actual argument used in the call.
This means that changes made to the parameter affect
the argument.

By default, C++ uses call by value to pass arguments. In general, this


means that code within a function cannot alter the arguments used to call
the function and above mentioned example while calling max() function
used the same method.

Default Values for Parameters:


When you define a function, you can specify a default value for each of the
last parameters. This value will be used if the corresponding argument is
left blank when calling to the function.

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;

int sum(int a,int b=20)


{

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;

// calling a function to add the values.


result= sum(a, b);
cout<<"Total value is :"<< result <<endl;

// calling a function again as follows.


result= sum(a);
cout<<"Total value is :"<< result <<endl;

return0;
}

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

Total value is:300


Total value is:120

C++ Arrays

Advertisements

44 | P a g e
Previous Page
Next Page

C++ provides a data structure, the array, which stores a fixed-size


sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ...,


and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last
element.

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];

This is called a single-dimension array. The arraySize must be an integer


constant greater than zero and type can be any valid C++ data type. For
example, to declare a 10-element array called balance of type double, use
this statement:

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:

Accessing Array Elements:


An element is accessed by indexing the array name. This is done by placing
the index of the element within square brackets after the name of the
array. For example:

double salary = balance[9];

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

// initialize elements of array n to 0


for(inti=0;i<10;i++)
{
n[i]=i+100;// set element at location i to i + 100
}
cout<<"Element"<<setw(13)<<"Value"<<endl;

// output each array element's value


for(int j =0; j <10; j++)
{
cout<<setw(7)<< j <<setw(13)<< n[ j ]<<endl;
}

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

C++ Arrays in Detail:


Arrays are important to C++ and should need lots of more detail. There are
following few important concepts, which should be clear to a C++
programmer:

Concept Description

C++ supports multidimensional arrays. The


Multi-dimensional arrays
simplest form of the multidimensional array is
the two-dimensional array.

You can generate a pointer to the first element


Pointer to an array
of an array by simply specifying the array name,
without any index.

You can pass to the function a pointer to an


Passing arrays to functions
array by specifying the array's name without an
index.

C++ allows a function to return an array.


Return array from
functions

C++ Strings

Advertisements

Previous Page
Next Page

C++ provides following two types of string representations:

• The C-style character string.

48 | P a g e
• The string class type introduced with Standard C++.

The C-Style Character String:


The C-style character string originated within the C language and continues
to be supported within C++. This string is actually a one-dimensional array
of characters which is terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed
by a null.

The following declaration and initialization create a string consisting of the


word "Hello". To hold the null character at the end of the array, the size of
the character array containing the string is one more than the number of
characters in the word "Hello."

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";

Following is the memory presentation of above defined string in C/C++:

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

cout<<"Greeting message: ";


cout<< greeting <<endl;

return0;
}

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


something as follows:

Greeting message:Hello

C++ supports a wide range of functions that manipulate null-terminated


strings:

S.N. Function & Purpose

1 strcpy(s1, s2);

Copies string s2 into string s1.

2 strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3 strlen(s1);

Returns the length of string 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);

Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above-mentioned functions:

#include<iostream>
#include<cstring>

usingnamespacestd;

int main ()
{
char str1[10]="Hello";
char str2[10]="World";
char str3[10];
intlen;

// copy str1 into str3


strcpy( str3, str1);
cout<<"strcpy( str3, str1) : "<< str3 <<endl;

// concatenates str1 and str2


strcat( str1, str2);
cout<<"strcat( str1, str2): "<< str1 <<endl;

// total lenghth of str1 after concatenation


len=strlen(str1);

51 | P a g e
cout<<"strlen(str1) : "<<len<<endl;

return0;
}

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


something as follows:

strcpy( str3, str1):Hello


strcat( str1, str2):HelloWorld
strlen(str1):10

The String Class in C++:


The standard C++ library provides a string class type that supports all the
operations mentioned above, additionally much more functionality. We will
study this class in C++ Standard Library but for now let us check following
example:

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;

// copy str1 into str3

52 | P a g e
str3 = str1;
cout<<"str3 : "<< str3 <<endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout<<"str1 + str2 : "<< str3 <<endl;

// total lenghth of str3 after concatenation


len= str3.size();
cout<<"str3.size() : "<<len<<endl;

return0;
}

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


something as follows:

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.

As you know every variable is a memory location and every memory


location has its address defined which can be accessed using ampersand (&)

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];

cout<<"Address of var1 variable: ";


cout<<&var1 <<endl;

cout<<"Address of var2 variable: ";


cout<<&var2 <<endl;

return0;
}

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


something as follows:

Address of var1 variable:0xbfebd5c0


Address of var2 variable:0xbfebd5b6

C++ Basic Input/Output

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.

I/O Library Header Files:


There are following header files important to C++ programs:

Header File Function and Description

<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.

<fstream> This file declares services for user-controlled file processing. We


will discuss about it in detail in File and Stream related chapter.

The standard output stream (cout):


The predefined object cout is an instance of ostream class. The cout
object is said to be "connected to" the standard output device, which
usually is the display screen. The cout is used in conjunction with the
stream insertion operator, which is written as << which are two less than
signs as shown in the following example.

#include<iostream>

55 | P a g e
usingnamespacestd;

int main()
{
charstr[]="Hello C++";

cout<<"Value of str is : "<<str<<endl;


}

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

Value of stris:Hello C++

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.

The standard input stream (cin):


The predefined object cin is an instance of istream class. The cin object is
said to be attached to the standard input device, which usually is the
keyboard. Thecin is used in conjunction with the stream extraction
operator, which is written as >> which are two greater than signs as shown
in the following example.

#include<iostream>

usingnamespacestd;

int main()

56 | P a g e
{
char name[50];

cout<<"Please enter your name: ";


cin>> name;
cout<<"Your name is: "<< name <<endl;

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:

Please enter your name:cplusplus


Your name is:cplusplus

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 >> age;

This will be equivalent to the following two statements:

cin>> name;
cin>> age;

The standard error stream (cerr):


The predefined object cerr is an instance of ostream class. The cerr object
is said to be attached to the standard error device, which is also a display
screen but the object cerr is un-buffered and each stream insertion to cerr
causes its output to appear immediately.

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....";

cerr<<"Error message : "<<str<<endl;


}

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

Errormessage :Unable to read....

C++ Classes and Objects

Advertisements

Previous Page
Next Page

The main purpose of C++ programming is to add object orientation to the C


programming language and classes are the central feature of C++ that
supports object-oriented programming and are often called user-defined
types.

A class is used to specify the form of an object and it combines data


representation and methods for manipulating that data into one neat
package. The data and functions within a class are called members of the
class.

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

The keyword public determines the access attributes of the members of


the class that follow it. A public member can be accessed from outside the
class anywhere within the scope of the class object. You can also specify
the members of a class as private or protected which we will discuss in a
sub-section.

Define C++ Objects:


A class provides the blueprints for objects, so basically an object is created
from a class. We declare objects of a class with exactly the same sort of
declaration that we declare variables of basic types. Following statements
declare two objects of class Box:

BoxBox1;// Declare Box1 of type Box


BoxBox2;// Declare Box2 of type 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

It is important to note that private and protected members can not be


accessed directly using direct member access operator (.). We will learn
how private and protected members can be accessed.

Classes & Objects in Detail:


So far, you have got very basic idea about C++ Classes and Objects. There
are further interesting concepts related to C++ Classes and Objects which
we will discuss in various sub-sections listed below:

Concept Description

A member function of a class is a function that


Class member functions
has its definition or its prototype within the class
definition like any other variable.

A class member can be defined as public, private


Class access modifiers
or protected. By default members would be
assumed as private.

A class constructor is a special function in a


Constructor & destructor
class that is called when a new object of the
class is created. A destructor is also a special

61 | P a g e
function which is called when created object is
deleted.

The copy constructor is a constructor which


C++ copy constructor
creates an object by initializing it with an object
of the same class, which has been created
previously.

A friend function is permitted full access to


C++ friend functions
private and protected members of a class.

With an inline function, the compiler tries to


C++ inline functions
expand the code in the body of the function in
place of a call to the function.

Every object has a special pointer this which


The this pointer in C++
points to the object itself.

A pointer to a class is done exactly the same


Pointer to C++ classes
way a pointer to a structure is. In fact a class is
really just a structure with functions in it.

Both data members and function members of a


Static members of a class
class can be declared as static.

C++ Inheritance

Advertisements

Previous Page
Next Page

One of the most important concepts in object-oriented programming is that


of inheritance. Inheritance allows us to define a class in terms of another
class, which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and fast
implementation time.

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.

The idea of inheritance implements the is a relationship. For example,


mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and
so on.

Base & Derived Classes:


A class can be derived from more than one classes, which means it can
inherit data and functions from multiple base classes. To define a derived
class, we use a class derivation list to specify the base class(es). A class
derivation list names one or more base classes and has the form:

class derived-class: access-specifierbase-class

Where access-specifier is one of public, protected, or private, and base-


class is the name of a previously defined class. If the access-specifier is not
used, then it is private by default.

Consider a base class Shape and its derived class Rectangle as follows:

#include<iostream>

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);

// Print the area of the object.


cout<<"Total area: "<<Rect.getArea()<<endl;

return0;
}

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

64 | P a g e
Total area:35

Access Control and Inheritance:


A derived class can access all the non-private members of its base class.
Thus base-class members that should not be accessible to the member
functions of derived classes should be declared private in the base class.

We can summarize the different access types according to who can access
them in the following way:

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no

A derived class inherits all base class methods with the following
exceptions:

• Constructors, destructors and copy constructors of the base class.

• Overloaded operators of the base class.

• The friend functions of the base class.

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.

We hardly use protected or private inheritance, but public inheritance is


commonly used. While using different type of inheritance, following rules
are applied:

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.

• Protected Inheritance: When deriving from a protected base


class,public and protected members of the base class
become protectedmembers of the derived class.

• Private Inheritance: When deriving from a private base


class,public and protected members of the base class
become privatemembers of the derived class.

Multiple Inheritances:
A C++ class can inherit members from more than one class and here is the
extended syntax:

class derived-class: access baseA, access baseB....

Where access is one of public, protected, or private and would be given


for every base class and they will be separated by comma as shown above.
Let us try the following example:

#include<iostream>

usingnamespacestd;

// Base class Shape


classShape
{
public:
voidsetWidth(int w)
{
width= w;

66 | P a g e
}
voidsetHeight(int h)
{
height= h;
}
protected:
int width;
int height;
};

// Base class PaintCost


classPaintCost
{
public:
intgetCost(int area)
{
return area *70;
}
};

// 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();

// Print the area of the object.


cout<<"Total area: "<<Rect.getArea()<<endl;

// Print the total cost of painting


cout<<"Total paint cost: $"<<Rect.getCost(area)<<endl;

return0;
}

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

Total area:35
Total paint cost: $2450

C++ Overloading (Operator and Function)

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).

When you call an overloaded function or operator, the compiler


determines the most appropriate definition to use by comparing the
argument types you used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the
most appropriate overloaded function or operator is called overload
resolution.

Function overloading in C++:


You can have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list. You can not
overload function declarations that differ only by return type.

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;

// Call print to print integer


pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");

return0;
}

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

Printingint:5
Printingfloat:500.263
Printing character:Hello C++

Operators overloading in C++:


You can redefine or overload most of the built-in operators available in
C++. Thus a programmer can use operators with user-defined types as
well.

Overloaded operators are functions with special names the keyword


operator followed by the symbol for the operator being defined. Like any
other function, an overloaded operator has a return type and a parameter
list.

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;

// Add two object as follows:


Box3=Box1+Box2;

// 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
& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which can not be overloaded:

:: .* . ?:

Operator Overloading Examples:


Here are various operator overloading examples to help you in
understanding the concept.

S.N. Operators and Example

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

The word polymorphism means having many forms. Typically,


polymorphism occurs when there is a hierarchy of classes and they are
related by inheritance.

C++ polymorphism means that a call to a member function will cause a


different function to be executed depending on the type of object that
invokes the function.

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);

// store the address of Rectangle


shape=&rec;
// call rectangle area.
shape->area();

// store the address of Triangle


shape=&tri;
// call triangle area.
shape->area();

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.

Pure Virtual Functions:


It's possible that you'd want to include a virtual function in a base class so
that it may be redefined in a derived class to suit the objects of that class,
but that there is no meaningful definition you could give for the function in
the base class.

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.

C++ Files and Streams

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:

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 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.

To perform file processing in C++, header files <iostream> and <fstream>


must be included in your C++ source file.

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.

Following is the standard syntax for open() function, which is a member of


fstream, ifstream, and ofstream objects.

void open(constchar*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.

80 | P a g e
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.

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.

Following is the standard syntax for close() function, which is a member of


fstream, ifstream, and ofstream objects.

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.

Reading from a File:


You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input information
from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.

Read & Write Example:


Following is the C++ program which opens a file in reading and writing
mode. After writing information inputted by the user to a file named
afile.dat, the program reads information from the file and outputs it onto
the screen:

#include<fstream>
#include<iostream>
usingnamespacestd;

int main ()
{

char data[100];

// open a file in write mode.


ofstreamoutfile;
outfile.open("afile.dat");

cout<<"Writing to the file"<<endl;

82 | P a g e
cout<<"Enter your name: ";
cin.getline(data,100);

// write inputted data into the file.


outfile<< data <<endl;

cout<<"Enter your age: ";


cin>> data;
cin.ignore();

// again write inputted data into the file.


outfile<< data <<endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstreaminfile;
infile.open("afile.dat");

cout<<"Reading from the file"<<endl;


infile>> data;

// write the data at the screen.


cout<< data <<endl;

// again read the data from the file and display it.
infile>> data;
cout<< data <<endl;

// close the opened file.


infile.close();

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.

File Position Pointers:


Both istream and ostream provide member functions for repositioning the
file-position pointer. These member functions are seekg ("seek get") for
istream and seekp ("seek put") for ostream.

The argument to seekg and seekp normally is a long integer. A second


argument can be specified to indicate the seek direction. The seek direction
can be ios::beg (the default) for positioning relative to the beginning of a
stream,ios::cur for positioning relative to the current position in a stream
or ios::endfor positioning relative to the end of a stream.

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:

// position to the nth byte of fileObject (assumes ios::beg)


fileObject.seekg( n );

// position n bytes forward in fileObject

84 | P a g e
fileObject.seekg( n,ios::cur );

// position n bytes back from end of fileObject


fileObject.seekg( n,ios::end);

// position at end of fileObject


fileObject.seekg(0,ios::end);

C++ Exception Handling

Advertisements

Previous Page
Next Page

An exception is a problem that arises during the execution of a program. A


C++ exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to


another. C++ exception handling is built upon three keywords: try,
catch, andthrow.

• throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

• catch: A program catches an exception with an exception handler at the place


in a program where you want to handle the problem. Thecatch keyword
indicates the catching of an exception.

• try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception


using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a
85 | P a g e
try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try
{
// protected code
}catch(ExceptionName e1 )
{
// catch block
}catch(ExceptionName e2 )
{
// catch block
}catch(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.

Following is an example of throwing an exception when dividing by zero


condition occurs:

double division(int a,int b)


{
if( b ==0)
{
throw"Division by zero condition!";

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
}

Above code will catch an exception of ExceptionName type. If you want to


specify that a catch block should handle any type of exception that is
thrown in a try block, you must put an ellipsis, ..., between the parentheses
enclosing the exception declaration as follows:

try
{
// protected code
}catch(...)
{
// code to handle any exception
}

The following is an example, which throws a division by zero exception and


we catch it in catch block.

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

Because we are raising an exception of type const char*, so while catching


this exception, we have to use const char* in catch block. If we compile and
run above code, this would produce the following result:

Divisionby zero condition!

C++ Standard Exceptions:

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:

Here is the small description of each exception mentioned in the above


hierarchy:

Exception Description

std::exception An exception and parent class of all the standard C++


exceptions.

std::bad_alloc This can be thrown by new.

89 | P a g e
std::bad_cast This can be thrown by dynamic_cast.

std::bad_exception This is useful device to handle unexpected exceptions in a


C++ program

std::bad_typeid This can be thrown by typeid.

std::logic_error An exception that theoretically can be detected by reading


the code.

std::domain_error This is an exception thrown when a mathematically invalid


domain is used

std::invalid_argument This is thrown due to invalid arguments.

std::length_error This is thrown when a too big std::string is created

std::out_of_range This can be thrown by the at method from for example a


std::vector and std::bitset<>::operator[]().

std::runtime_error An exception that theoretically can not be detected by


reading the code.

std::overflow_error This is thrown if a mathematical overflow occurs.

std::range_error This is occured when you try to store a value which is out
of range.

std::underflow_error This is thrown if a mathematical underflow occurs.

Define New Exceptions:


You can define your own exceptions by inheriting and
overriding exceptionclass functionality. Following is the example, which
90 | P a g e
shows how you can use std::exception class to implement your own
exception in standard way:

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

This would produce the following result:

91 | P a g e
MyException caught
C++Exception

Here, what() is a public method provided by exception class and it has


been overridden by all the child exception classes. This returns the cause of
an exception.

C++ Templates

Advertisements

Previous Page
Next Page

Templates are the foundation of generic programming, which involves


writing code in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or a


function. The library containers like iterators and algorithms are examples
of generic programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can


define many different kinds of vectors for example, vector <int> or vector
<string>.

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:

template<class type> ret-type func-name(parameter list)


{
// body of function
}

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.

The following is the example of a function template that returns the


maximum of two values:

#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.

Following is the example to define class Stack<> and implement generic


methods to push and pop the elements from the stack:

#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

// manipulate int stack


intStack.push(7);
cout<<intStack.top()<<endl;

// manipulate string stack


stringStack.push("hello");
cout<<stringStack.top()<<std::endl;
stringStack.pop();
stringStack.pop();
}
catch(exception const& ex){
cerr<<"Exception: "<<ex.what()<<endl;
return-1;
}
}

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