You are on page 1of 36

Object Oriented Programming Language in C++

Introduction to C++
C++, as we all know is an extension to C language and was developed by BJARNE STROUSTRUP, AT
BELL LABS. C++ is an intermediate level language, as it comprises a confirmation of both high level
and low level language features. C++ is a statically typed, free form, multiparadigm, compiled generalpurpose language. C++ is an Object Oriented Programming language but is not purely Object Oriented. Its
features like Friend and Virtual, violate some of the very important OOPS features, rendering this
language unworthy of being called completely Object Oriented. Its a middle level language.

Benefits of C++ over C Language


The major difference being OOPS concept, C++ is an object oriented language whereas C language is a
procedural language. Apart form this there are many other features of C++ which gives this language an
upper hand on C laguage.
Following features of C++ makes it a stronger language than C,

There is Stronger Type Checking in C++.


All the OOPS features in C++ like Abstraction, Encapsulation, Inheritance etc makes it more worthy
and useful for programmers.
C++ supports and allows user defined operators (i.e Operator Overloading) and function overloading
is also supported in it.
Exception Handling is there in C++.
The Concept of Virtual functions and also Constructors and Destructors for Objects.
Inline Functions in C++ instead of Macros in C language. Inline functions make complete function
body act like Macro, safely.
Variables can be declared anywhere in the program in C++, but must be declared before they are used.

Object Oriented programming is a programming style that is associated with the concept of OBJECTS,
having datafields and related member functions. Objects are instances of classes and are used to interact
amongst each other to create applications. Instance means, the object of class on which we are currently
working. C++ can be said to be as C language with classes. In C++ everything revolves around object of
class, which have their methods & data members. C++ can be said to be as C language with classes. In
C++ everything revolves around object of class, which have their methods & data members. We consider
human body as a class, we do have multiple objects of this class, with variable as color, nose, eye and hair
etc. and methods as walking, speaking etc.
Now, let us discuss some of the main features of object oriented programming which you will be using in
C++.
Objects: Objects are the basic unit of OOP. They are instances of class, which have data members and
uses various member functions to perform tasks. Objects are identified by its unique name. An object
represents a particular instance of a class. There can be more than one instance of a class. Each instance of
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 1

Object Oriented Programming Language in C++

a class can hold its own relevant data. An Object is a collection of data members and associated member
functions also known as methods.
Classes: It is similar to structures in C language. Class can also be defined as user defined data type but it
also contains functions in it. So, class is basically a blueprint for object. It declare and defines what data
variables the object will have and what operations can be performed on the class's object. Classes are data
types based on which objects are created. Objects with similar properties and methods are grouped
together to form a Class. Thus a Class represents a set of individual objects. Characteristics of an object
are represented in a class as Properties. The actions that can be performed by objects become functions of
the class and are referred to as Methods.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents
individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Color,
Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e.,
object functions like Start, Move, and Stop form the Methods of Car Class.
No memory is allocated when a class is created. Memory is allocated only when an object is created, i.e.,
when an instance of a class is created.
Inheritance: Inheritance is the process of forming a new class from an existing class or base class. The
base class is also known as parent class or super class. The new class that is formed is called derived class.
Derived class is also known as a child class or sub class. Inheritance helps in reducing the overall code
size of the program, which is an important concept in object-oriented programming.
Data Abstraction: Abstraction refers to showing only the essential features of the application and hiding
the details. In C++, classes provide methods to the outside world to access & use the data variables, but
the variables are hidden from direct access. Data Abstraction increases the power of programming
language by creating user defined data types. Data Abstraction also represents the needed information in
the program without presenting the details.
Data Encapsulation: It can also be said data binding. Encapsulation is all about binding the data variables
and functions together in class. Data Encapsulation combines data and functions into a single unit called
Class. When using Data Encapsulation, data is not accessed directly; it is only accessible through the
functions present inside the class. Data Encapsulation enables the important concept of data hiding
possible.
Polymorphism: Polymorphion makes the code more readable. It is a features, which lets is create
functions with same name but different arguments, which will perform differently. That is function with
same name, functioning in different. Polymorphism allows routines to use variables of different types at
different times. An operator or function can be given different meanings or functions. Polymorphism
refers to a single function or multi-functioning operator performing in different ways.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 2

Object Oriented Programming Language in C++

Overloading: Overloading is a part of polymorphion. Where a function or operator is made & defined
many times, to perform different functions they are said to be overloaded. Overloading is one type of
Polymorphism. It allows an object to have different meanings, depending on its context. When an existing
operator or function begins to operate on new data type, or class, it is understood to be overloaded.
Reusability: This term refers to the ability for multiple programmers to use the same written and
debugged existing class of data. This is a time saving device and adds code efficiency to the language.
Additionally, the programmer can incorporate new features to the existing class, further developing the
application and allowing users to achieve increased performance. This time saving feature optimizes code,
helps in gaining secured applications and facilitates easier maintenance on the application.

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.h> // 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.
int main( )
{
char str[] = "Hello Bimal Kumar";
cout << "Value of string is : " << str << endl;
}

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. The cin 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.
void main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
getch();
}
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;
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 3

Object Oriented Programming Language in C++

What is Variables:
 Variable are used in C++, where we need storage for any value, which will change in program.
 Variable can be declared in multiple ways each with different memory requirements and functioning.
 Variable is the name of memory location allocated by the compiler depending upon the datatype of the
variable.
 A variable is the content of a memory location that stores a certain value.
 A variable is identified or denoted by a variable name.
 The variable name is a sequence of one or more letters, digits or underscore.
Rules for defining variable name:

A variable name can have one or more letters or digits or underscore for example character_.
White space, punctuation symbols or other characters are not permitted to denote variable name.
A variable name must begin with a letter.
Variable names cannot be keywords or any reserved words of the C++ programming language.
Data C++ is a case-sensitive language. Variable names written in capital letters differ from variable
names with the same name but written in small letters.

Data Types: The most commonly used Data Types in C++ programming language:
short int This data type is used to represent short integer.
int This data type is used to represent integer.
long int This data type is used to represent long integer.
float This data type is used to represent floating point number.
double This data type is used to represent double precision floating point number.
long double This data type is used to represent double precision floating point number.
char This data type is used to represent a single character.
bool This data type is used to represent boolean value. It can take one of two values: True or False.
Type
char
unsigned char
signed char
int
unsigned int
signed int
short int
unsigned short int

Typical Bit Width


1byte
1byte
1byte
4bytes
4bytes
4bytes
2bytes
Range

Typical Range
-127 to 127 or 0 to 255
0 to 255
-127 to 127
-2147483648 to 2147483647
0 to 4294967295
-2147483648 to 2147483647
-32768 to 32767
0 to 65,535

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 4

Object Oriented Programming Language in C++

signed short int

Range

long int
signed long int
unsigned long int
float
double
long double
wchar_t

4bytes
4bytes
4bytes
4bytes
8bytes
8bytes
2 or 4 bytes

-32768 to 32767
-2,147,483,647 to
2,147,483,647
same as long int
0 to 4,294,967,295
+/- 3.4e +/- 38 (~7 digits)
+/- 1.7e +/- 308 (~15 digits)
+/- 1.7e +/- 308 (~15 digits)
1 wide character

Declaring Variables
Each variable while declaration must be given a datatype, on which the memory assigned to the variable
depends. In order for a variable to be used in C++ programming language, the variable must first be
declared. The syntax for declaring variable names is: data type <variable_name>;
Example: int x; This declares a variable name x of type int.
The date type can be int or float or any of the data types listed above. A variable name is given based on
the rules for defining variable name (refer above rules). If there exists more than one variable of the same
type, such variables can be represented by separating variable names using comma. For instance int x,y,z
This declares 3 variables x, y and z all of data type int.
Scope of Variables
All the variables have their area of functioning, and out of that boundary they don't hold their value, this
boundary is called scope of the variable. For most of the cases its between the curly braces,in which
variable is declared that a variable exists, not outside it. We will study the storage classes later, but as of
now, we can broadly divide variables into two main types.
1. Global variables
Global variables are those, which ar once declared and can be used throughout the lifetime of the program
by any class or any function. They must be declared outside the main() function. If only declared, they can
be assigned different values at different time in program lifetime. But even if they are declared and
initialized at the same time outside the main() function, then also they can be assigned any value at any
point in the program.
Example : Only declared, not initialized
int x;
// Global variable declared
int main()
{
x=10;
// Initialized once
cout <<"first value of x = "<< x;
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 5

Object Oriented Programming Language in C++

x=20;
// Initialized again
cout <<"Initialized again with value = "<< x;
}
2. Local Variables
Local variables are the variables which exist only between the curly braces, in which its declared. Outside
that they are unavailable and leads to compile time error. Example :
int main()
{
int i=10;
if(i<20)
// if condition scope starts
{
int n=100; // Local variable declared and initialized
}
// if condition scope ends
cout << n;
//Compile time error, n not available here
}
Some special types of variable: There are also some special keywords, to impart unique characteristics to
the variables in the program. Following two are mostly used, we will discuss them in details later.
Final: Once initialized, its value cant be changed.
Static: These variables holds their value between function calls.
Examples
int main()
{
final int i=10;
static int y=20;
{ }
}
Constants
Constants have fixed value. Constants, like variables, contain data type. Integer constants are represented
as decimal notation, octal notation, and hexadecimal notation. Decimal notation is represented with a
number. Octal notation is represented with the number preceded by a zero character. A hexadecimal
number is preceded with the characters 0x.

OPERATORS AVAILABLE IN C++


The operators available in C++ programming language are:
 Assignment Operator ( = )
This is denoted by symbol =. This operator is used for assigning a value to a variable. The left of
the assignation operator is known as the lvalue (left value), which must be a variable.
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 6

Object Oriented Programming Language in C++

The right of the assignation operator is known as the rvalue (right value). The rvalue can be a constant, a
variable, the result of an operation or any combination of these.
For example: x = 5;
 Arithmetic operators denoted by +, -, *, /, %
 Compound assignment Operators denoted by +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=
 Increment and Decrement operator denoted by ++, - Relational and equality operators denoted by ==, !=, >, <, >=, <=
 Logical operators denoted by !, &&, ||
The operator && corresponds with Boolean logical operation AND. This operator returns the
value of true only if both its operands are true or else it returns false.
The operator || corresponds with Boolean logical operation OR. The operator returns a true
value if either one of its two operands is true and returns a false value only when both operands
are false.
The operator ! is called NOT operator. This has a single operand which reverses its value.
 Conditional operator denoted by ?,:
The conditional operator evaluates an expression returning value1 if that expression is true and
value2 if the expression is evaluated as false. The syntax is: condition ? value1 : value2
For example: 7>5 ? x : y
Since 7 is greater than 5, true is returned and hence the value x is returned.
 Comma operator denoted by ,
This is denoted by , and it is used to separate two or more expressions.
 Bitwise Operators denoted by &, |, ^, ~, <<, >>
 Explicit type casting operator

Decision statements in C++


Decision making is about deciding the order of execution of statements based on certain conditions or
repeat a group of statements until certain specified conditions are met. 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 from of a typical decision making structure found in most of the programming
languages:

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 7

Object Oriented Programming Language in C++

C++ programming language provides following types of decision making statements.


An IF STATEMENT consists of a boolean expression followed by one or more statements.
The syntax of an if statement in C++ is:
if(boolean_expression)
{
statement(s); // will execute if the boolean expression is true
}
If the boolean expression evaluates to true, then the block of code inside the if statement will be executed.
If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
Flow Diagram:

Example:
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 8

Object Oriented Programming Language in C++

#include <iostream.h>
#include <conio.h>
void main ()
{
int a = 5;
if( a < 200 ) // check the boolean condition
{
cout << "a is less than 200;" << endl; // if condition is true then print the following
}
cout << "value of a is : " << a << endl;
getch();
}
An IF STATEMENT can be followed by an optional ELSE statement, which executes when the boolean
expression is false. The syntax of an if...else statement in C++ is:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block
of code will be executed.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 9

Object Oriented Programming Language in C++

Examples for IF - ELSE statement


void main ()
{
int a = 7; // local variable declaration:
clrscr(); // clear the output screen
if( a %2==0) // check the boolean condition
{
cout << "this is even number" << endl; // if condition is true then print the following
}
else
{
cout << "this is odd number;" << endl; // if condition is false then print the following
}
cout << "value of a is : " << a << endl;
getch();
}

THE IF...ELSE IF...ELSE STATEMENT:


An if statement can be followed by an optional else if...else statement, which is very usefull to test various
conditions using single if...else if statement. When using if , else if , else statements there are few points to
keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax: The syntax of an if...else if...else statement in C++ is:
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 10

Object Oriented Programming Language in C++

else
{
// executes when the none of the above condition is true.
}
Examples
void main ()
{
int a = 100;
if( a == 10 )
{
cout << "Value of a is 10" << endl;
}
else if( a == 20 )
{
cout << "Value of a is 20" << endl;
}
else if( a == 30 )
{
cout << "Value of a is 30" << endl;
}
else
{
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
getch();
}
NEST IF-ELSE STATEMENTS
It is always legal to nest if-else statements, which means you can use one if or else if statement inside
another if or else if statement(s). The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}
You can nest else if...else in the similar way as you have nested if statement.
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 11

Object Oriented Programming Language in C++

SWITCH STATEMENT
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each case.
The syntax for a switch statement in C++ is as follows:
switch(expression)
{
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
// you can have any number of case statements.
default : //Optional
statement(s);
}

Flow Diagram:

The following rules apply to a switch statement:

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 12

Object Oriented Programming Language in C++

 The expression used in a switch statement must have an integral or enumerated type, or be of a class
type in which the class has a single conversion function to an integral or enumerated type.
 You can have any number of case statements within a switch. Each case is followed by the value to be
compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the switch, and it must
be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will execute
until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall through to
subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the switch. The
default case can be used for performing a task when none of the cases is true. No break is needed in
the default case.
Example for switch case
void main ()
{
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 13

Object Oriented Programming Language in C++

default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
getch();
}
LOOPING in C++
In any programming language, loops are used to execute a set of statements repeatedly until a particular
condition is satisfied. 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 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.

How it works

A sequence of statement is executed until a specified condition is true. This sequence of statement to be
executed is kept inside the curly braces { } known as loop body. After every execution of loop body,
condition is checked, and if it is found to be true the loop body is executed again. When condition check
comes out to be false, the loop body will not be executed.
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 14

Object Oriented Programming Language in C++

WHILE LOOP
 Repeats a statement or group of statements while a given condition is true. It tests the condition before
executing the loop body.
 A while loop statement repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in C++ is:
variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true. examples
void main ()
{
int a = 1;
while( a < 20 ) // while loop execution
{
cout << "value of a: " << a << endl;
a++;
}
getch();
}
DO WHILE LOOP
 Like a while statement, except that it tests the condition at the end of the loop body.
 In some situations it is necessary to execute body of the loop before testing the condition. Such
situations can be handled with the help of do-while loop. do statement evaluates the body of the loop
first and at the end, the condition is checked using while statement.
 A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
The syntax of a do...while loop in C++
do
{
statement(s);
.....
variable increment or decrement ;
}while(condition);
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 15

Object Oriented Programming Language in C++

Examples for do while looping


void main ()
{
int a = 100;
do
{
cout << "value of a: " <<a;
a++;
} while( a >=1 );
getch();
}
FOR LOOP
Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute
a specific number of times.
The syntax of a for loop in C++ is:
for ( initialize; condition; increment/decrement )
{
statement(s);
}
Here is the flow of control in a for loop:

The initialize step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the for
loop.
After the body of the for loop executes, the flow of control jumps back up to the
increment/decrement statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the for loop terminates.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 16

Object Oriented Programming Language in C++

In for loop we have exactly two semicolons, one after initialization and second after condition. In
this loop we can have more than one initialization or increment/decrement, separated using comma
operator. For loop can have only one condition.
For examples For Loop
void main ()
{
for( int a = 1; a < 20; a = a + 1 )
{
cout << "value of a: " << a ;
}
getch();
}

NESTE LOOPING
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
The syntax for a nested for loop statement in C++ is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested while loop statement in C++ is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a nested do...while loop statement in C++ is as follows:

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 17

Object Oriented Programming Language in C++

do
{
statement(s); // you can put more statements.
do
{
statement(s);
}while( condition );
}while( condition );
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100.
void main ()
{
int i, j;
for(i=2; i<100; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j))
break; // if factor found, not prime
if(j > (i/j))
cout << i << " is prime\n";
}
getch();
}

Jumping out of loop: Sometimes, while executing a loop, it becomes necessary to skip a part of the
loop or to leave the loop as soon as certain condition becocmes true, that is jump out of loop. C language
allows jumping from one statement to another within a loop as well as jumping out of the loop.

break statement: When break statement is encountered inside a loop, the loop is immediately exited
and the program continues with the statement immediately following the loop.

continue statement: It causes the control to go directly to the test-condition and then continue the
loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next
cycle.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 18

Object Oriented Programming Language in C++

ARRAY
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: type arrayName [ arraySize ];
This is called a single-dimension array. The array Size 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:
Int balance[5] = {52,42,69,25,55};
The number of values between braces { } can not be larger than the number of elements that we declare
for the array between square brackets [ ].
void main ()
{
int n[ 10 ]; // n is an array of 10 integers
for ( int i = 0; i < 10; i++ ) // initialize elements of array n to 0
{
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
for ( int j = 0; j < 10; j++ ) // output each array element's value
{
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
getch();
}
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 19

Object Oriented Programming Language in C++

Classes in C++

A class is the collection of related data and function under a single name.
A class is nothing but grouping of variables of different data types with function. Each variable of
class is called as member variable. Functions are called as member functions or methods.
A class is an expanded concept of a data structure instead of holding only data, it can hold both data
and functions.
A class is a user defined type or data structure declared with keyword class that has data and functions
as its members whose access is governed by the three access specifiers private, protected and public
(by default access to members of a class is private).
The Private Members are not accessible outside the class; they can be accessed only through methods
of the class.
The Public Members form an interface to the class and are accessible outside the class.
Instances of these data types are known as objects and can contain member variables, constants,
member functions, and overloaded operators defined by the programmer.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object
would be the variable.
Objects are essentially the variables and Classes are the types of their values.

Classes are generally declared using the keyword class, with the following format:
class class_name
{
access_specifier_1:
member variable1;
member function1;
access_specifier_2:
member variable 2;
member function2;
} object_names;
Classes declared another format:
Class <name of class>
{
Private:
Declaration of variable;
Prototype declaration of functions;
Public:
Declaration of variable;
Prototype declaration of functions;
};
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects
of this class. The body of the declaration can contain members, that can be either data or function
declarations, and optionally access specifiers.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 20

Object Oriented Programming Language in C++

All is very similar to the declaration on data structures, except that we can now include also functions and
members, but also this new thing called access specifier. An access specifier is one of the following three
keywords: private, public or protected. These specifiers modify the access rights that the members
following them acquire:

private members of a class are accessible only from within other members of the same class or
from their friends.
protected members are accessible from members of their same class and from their friends, but
also from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.

By default, all members of a class declared with the class keyword have private access for all its members.
Therefore, any member that is declared before one other class specifier automatically has private access.
// Simple program to read Student details and to output the data
#include < iostream.h>
// Preprocessor directive
#include < conio.h>
class student
// Class Declaration
{
private:
char name[50];
int rollno;
public:
void getinput ()
{
cout<<"Enter the student Rollno: ";
cin>>rollno; // waiting input from the Keyboard for the rollno
cout<<"Enter the student Name: ";
cin>>name; // waiting input from the Keyboard for the name
}
void displayoutput()
{
cout<<"Student Rollno :"<< rollno << endl; // displays the student rollno
cout<<"Name of the Student :"<< name << endl; // displays the student name
}
}; // End Class Declaration
void main()
{
Student obj; // Creation of Object
obj.getinput(); // the getinput method is being called
obj.displayoutput(); // the displayoutput method is being called
}
The // in first line is used for representing comment in the program.
The second line of the program has a # symbol which represents the preprocessor directive followed
by header file to be included placed between < >.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 21

Object Oriented Programming Language in C++

The next structure present in the program is the class definition. This starts with the keyword class
followed by class name employee. Within the class are data and functions. The data defined in the
class are generally private and functions are public. The class declaration ends with a semicolon.
main() function is present in all C++ programs.
An object obj is created in stusent class. Using this obj the functions present in the student class are
accessed and there by data are accessed.
The input named rollno and name is received using the input statement named cin and the values are
outputted using the output statement named cout.

Access Controls in Classes


Access specifiers in C++ class defines the access control rules. C++ has 3 new keywords introduced,
namely Public ,private and protected. These access specifiers are used to set boundaries for availability of
members of class be it data members or member functions. Access specifiers in the program, are followed
by a colon. You can use either one, two or all 3 specifiers in the same class to set different boundaries for
different class members. They change the boundary for all the declarations that follow them.
Public: Public means all the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. Hence there are
chances that they might change them. So the key members must not be declared public.
class bk
{
public: // public access specifier
int x;
// Data Member Declaration
void display(); // Member Function decaration
};
Private: Private keyword, means that no one can access the class members declared private outside that
class. If someone tries to access the private member, they will get a compile time error. By default class
variables and member functions are private.
class BK
{
private: // private access specifier
float y;
// Data Member Declaration
void show(); // Member Function decaration
};
Protected: Protected is the last access specifier, and it is similar to private, it makes class member
inaccessible outside the class. But they can be accessed by any subclass of that class.
class bim
{
protected: // protected access specifier
int x;
// Data Member Declaration
void display(); // Member Function decaration
};

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 22

Object Oriented Programming Language in C++

Member Functions in Classes


Member functions are the functions, which have their declaration inside the class definition and works on
the data members of the class. The definition of member functions can be inside or outside the definition
of class. If the member function is defined inside the class definition it can be defined directly, but if its
defined outside the class, then we have to use the scope resolution:: operator along with class name alng
with function name.
Example
class Cube
{
public:
int side;
int getVolume(); // Declaring function getVolume with no argument and return type int.
};
If we define the function inside class then we don't not need to declare it first, we can directly define the
function.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side;
//returns volume of cube
}
};
But if we plan to define the member function outside the class definition then we must declare the
function inside class definition and then define it outside.
class Cube
{
public:
int side;
int getVolume();
}
int Cube :: getVolume() // defined outside class definition
{
return side*side*side;
}
The maine function for both the function definition will be same. Inside main() we will create object of
class, and will call the member function using dot(.) operator.
int main()
{
Cube C1;
C1.side=4; // setting side value
cout<< "Volume of cube C1 ="<< C1.getVolume();
}
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 23

Object Oriented Programming Language in C++

Similarly we can define the getter and setter functions to access private data members, inside or outside
the class definition.

Types of Member Functions


We already know what member functions are and what they do. Now lets study some special member
functins present in the class. Following are different types of Member functions.

Simple Member Functions


These are the basic member function, which dont have any special keyword like static etc as prefix. All
the general member functions, which are of below given form, are termed as simple and basic member
functions.
return_type functionName(parameter_list)
{
function body;
}

Static Member Functions


Static is something that holds its position. Static is a keyword which can be used with data members as
well as the member functions. We will discuss this in details later. As of now we will discuss its usage
with member functions only.
A function is made static by using static keyword with function name. These functions work for the class
as whole rather than for a particular object of a class.
It can be called using the object and the direct member access dot (.) operator. But, its more typical to call
a static member function by itself, using class name and scope resolution ( :: ) operator.
Example
class X
{
public:
static void bk(){};
};
int main()
{
X::bk(); // calling member function directly with class name
}
These functions cannot access ordinary data members and member functions, but only static data members
and static member functions.
It doesn't have any "this" keyword which is the reason it cannot access ordinary members. We will study
about "this" keyword later.

Const Member Functions


We will study Const keyword in detail later, but as an introduction, Const keyword makes variables
constant, that means once defined, there values can't be changed.
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 24

Object Oriented Programming Language in C++

When used with member function, such member functions can never modify the object or its related data
members.
//Basic Syntax of const Member Function
void fun() const {}

Inline Functions
All the member functions defined inside the class definition are by default declared as Inline. All the
member functions defined inside the class definition are by default declared as Inline.
You must remember Preprocessors from C language. Inline functions in C++ do the same thing what
Macros do in C. Preprocessors were not used in C++ because they had some drawbacks.
In Macro, we define certain variable with its value at the beginning of the program, and everywhere inside
the program where we use that variable, its replaced by its value on Compilation.
Inline functions are actual functions, which are copied everywhere during compilation, like preprocessor
macro, so the overhead of function calling is reduced. All the functions defined inside class definition are
by default inline, but you can also make any non-class function inline by using keyword inline with them.
For an inline function, declaration and definition must be done together. For example,
inline void fun(int a)
{
return a++;
}

Limitations of Inline Functions


 The compiler is unable to perform inlining if the function is too complicated. So we must avoid big
looping conditions inside such functions. In case of inline functions, entire function body is inserted in
place of each call, so if the function is large it will affect speed and memory badly.
 if we require address of the function in program, compiler cannot perform inlining on such functions.
Because for providing address to a function, compiler will have to allocate storage to it. But inline
functions doesn't get storage, they are kept in Symbol table.

Friend Functions
Friend functions are actually not class member function. Friend functions are made to give private access
to non-class functions. You can declare a global function as friend, or a member function of other class as
friend.
Example :
class WithFriend
{
int i;
public:
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 25

Object Oriented Programming Language in C++

friend void fun(); // Global function as friend


};
void fun()
{
WithFriend wf;
wf.i=10; // Access to private data member
cout << wf.i;
}
int main()
{
fun(); //Can be called directly
}
Hence, friend functions can access private data members by creating object of the class. Similarly we can
also make function of other class as friend, or we can also make an entire class as friend class.
class Other
{
void fun();
};
class WithFriend
{
private:
int i;
public:
void getdata(); // Member function of class WithFriend
friend void Other::fun(); // making function of class Other as friend here
friend class Other; // making the complete class as friend
};
When we make a class as friend, all its member functions automatically become friend functions.
Friend Functions is a reason, why C++ is not called as a pure Object Oriented language. Because it
violates the concept of Encapsulation.

FUNCTION OVERLOADING IN C++


If any class have multiple functions with same names but different parameters then they are said to be
overloaded. Function overloading allows you to use the same name for different functions, to perform,
either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have to perform one
single operation but with different number or types of arguments, then you can simply overload the
function.

Number Of Arguments Different


In this type of function overloading we define two functions with same names but different number of
parameters of the same type. For example, in the below mentioned program we have made two sum()
functions to return sum of two and three integers.
Examples
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 26

Object Oriented Programming Language in C++

int sum (int x, int y)


{
cout << x+y;
}
int sum(int x, int y, int z)
{
cout << x+y+z;
}
int main()
{
sum (10,20); // sum() with 2 parameter will be called
sum(10,20,30); //sum() with 3 parameter will be called
}
Here sum() function is overloaded, to have two and three arguments. Which sum() function will be called,
depends on the number of arguments.

Different Datatype of Arguments


In this type of overloading we define two or more functions with same name and same number of
parameters, but the type of parameter is different. For example in this program, we have two sum()
function, first one gets two integer arguments and second one gets two double arguments.
Examples
int sum(int x,int y)
{
cout<< x+y;
}
double sum(double x,double y)
{
cout << x+y;
}
int main()
{
sum (10,20);
sum(10.5,20.5);
}

Default Arguments
When we mention a default value for a parameter while declaring the function, it is said to be as default
argument. In this case, even if we make a call to the function without passing any value for that parameter,
the function will take the default value specified.
sum(int x,int y=0) //Here we have provided a default value for y, during function definition.
{
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 27

Object Oriented Programming Language in C++

cout << x+y;


}
int main()
{
sum(10);
sum(10,0);
sum(10,10);
}
// simple examples for function overloading
#include <iostream.h>
#include <conio.h>
class bk
{
public:
void print(int i)
{
cout << "Printing int: " << i ;
}
void print(double f)
{
cout << "Printing float: " << f ;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
bk ru;
clrscr();
ru.print(7); // Call print to print integer
ru.print(179.143); // Call print to print float
ru.print("Welcome to C++ Language"); // Call print to print character
getch();
}

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.

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 28

Object Oriented Programming Language in C++

// simple program for operator overloading


#include <iostream.h>
#include <conio.h>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
Box operator+(const Box& b) // Overload + operator to add two Box objects.
{
Box box;
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
};
int main( )
{
Box Box1;
// Declare Box1 of type Box
Box Box2;
// Declare Box2 of type Box
Box Box3;
// Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
Box1.setLength(6.0); // box 1 specification
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 29

Object Oriented Programming Language in C++

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;
getch();
}
// simple program using relational operator
#include <iostream.h>
#include <conio.h>
using namespace std;
class Distance
{
private:
int feet;
// 0 to infinite
int inches;
// 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 30

Object Oriented Programming Language in C++

return Distance(feet, inches);


}
// overloaded < operator
bool operator <(const Distance& d)
{
if(feet < d.feet)
{
return true;
}
if(feet == d.feet && inches < d.inches)
{
return true;
}
return false;
}
};
int main()
{
Distance D1(11, 10), D2(5, 11);
if( D1 < D2 )
{
cout << "D1 is less than D2 " << endl;
}
else
{
cout << "D2 is less than D1 " << endl;
}
getch();
}

CONSTRUCTORS
Constructors are special class functions which performs initialization of every object. The Compiler calls
the Constructor whenever an object is created. Constructors iitialize values to object members after
storage is allocated to the object.
While defining a contructor you must remeber that the name of constructor will be same as the name of
the class, and contructors never have return type.

class A
{
int x;
public:
A(); //Constructor
};
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 31

Object Oriented Programming Language in C++

Constructors can be defined either inside the class definition or outside class definition using class name
and scope resolution (::) operator.
class A
{
int i;
public:
A(); //Constructor declared
};
A::A() // Constructor definition
{
i=1;
}
Types of Constructors in C++
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax :
Class class_name
{
class_name ()
{
Constructor Definition
}
};
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}

Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 32

Object Oriented Programming Language in C++

In this case, as soon as the object is created the constructor is called which initializes its data members.
A default constructor is so important for initialization of object members, that even if we do not define a
constructor explicitly, the compiler will provide a default constructor implicitly.

Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different values to data
members of different objects, by passing the appropriate values as argument. Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
By using parameterized construcor in above case, we have initialized 3 objects with user defined values.
We can have any number of parameters in a constructor.

Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy values of
data members of one object into other object.

Constructor Overloading
Just like other member functions, constructors can also be overloaded. Infact when you have both default
and parameterized constructors defined in your class you are having Overloaded Constructors, one with no
parameter and other with parameter.
a constructor can also be overloaded with more than one function that have the same name but different
types or number of parameters. Remember that for overloaded functions the compiler will call the one
whose parameters match the arguments used in the function call. In the case of constructors, which are
automatically called when an object is created, the one executed is the one that matches the arguments
passed on the object declaration:
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 33

Object Oriented Programming Language in C++

class Student
{
int rollno;
char name[20];
public:
Student(int x)
{
rollno=x;
name=" ";
}
Student(int x, char str[20])
{
rollno=x ;
name=str ;
}
};
int main()
{
Student A(10);
Student B(11," Hare Ram");
}
In above case we have defined two constructors with different parameters, hence overloading the
constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not provide
default constructor and you will have to define it yourself.
In the above case if we write Student S in main() it will lead to a compile time error, because we haven't
defined default constructor, and compiler will not provide its default constructor because we have defined
other parameterized constructors.
// example overloading class constructors calculate area of rectangle
#include <iostream.h>
#include <conio.h>
class Rect1
{
int width, height;
public:
Rect1 ();
Rect1 (int,int);
int area (void) {return (width*height);}
};
Rect1::Rect1 ()
{
width = 5;
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 34

Object Oriented Programming Language in C++

height = 5;
}
Rect1::Rect1 (int a, int b)
{
width = a;
height = b;
}
void main ()
{
Rect1 rect (3,4);
Rect1 rectb;
cout << "rect area: " << rect.area();
cout << "rectb area: " << rectb.area();
getch();
}

DESTRUCTORS
Destructor is a special class function which destroys the object as soon as the scope of object ends. The
destructor is called automatically by the compiler when the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is used for the name of
destructor, with a tilde( ~ ) sign as prefix to it.
class A
{
public:
~A();
};
Example to see how Constructor and Destructor is called
class A
{
A()
{
cout << "Constructor called";
}
~A()
{
cout << "Destructor called";
}
};
void main()
{
A obj1; // Constructor Called
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 35

Object Oriented Programming Language in C++

int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
getch();
} // Destructor called for obj1

// example on constructors and destructors


#include <iostream.h>
#include <conio.h>
using namespace std;
class Rect
{
int *width, *height;
public:
Rect (int,int);
~Rect ();
int area ()
{
return (*width * *height);
}
};
Rect::Rect (int a, int b)
{
width = new int;
height = new int;
*width = a;
*height = b;
}
Rect::~Rect ()
{
delete width;
delete height;
}
void main ()
{
clrscr();
Rect rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
getch();
}
Prepared By: Mr. B. K. Ray Dept. of IST/ETC, Ravenshaw University

Page 36

You might also like