C++ Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 123

OBJECT ORIENTED PROGRAMMING

WITH C++
Course Code: 16ECE71
Credits: 03
Semester: V
Total Contact Hours: 39
SEE Marks: 50
CIE Marks: 50
1
Duration of SEE: 03 hrs
Course Outcomes
A student who successfully fulfills the course requirements will have
demonstrated:
 Explain the basic principles and features of object-oriented
programming using C++ and hence analyze the given program.
 Illustrate the concepts of functions, classes and objects using object-
oriented programming with C++.
 Illustrate the concepts of inheritance and polymorphism to write a
program using C++.
 Illustrate I/O and File management techniques using the concepts of
stream classes in C++.
 Apply the concepts of exception handling and templates to write a
program using C++.
2
COURSE CONTENT
UNIT-I
 Principles of OOP: OOP paradigm, Procedural Vs. Object
Oriented Programming, Benefits and applications of OOP.
 C++ Features: Program structure, namespace, identifiers,
variables, constants, enum, operators, typecasting, control
structures.
 C++ Functions: Call and Return by reference, Inline functions,
Overloading of functions, default arguments.
 Objects and classes : Basics of object and class in C++, Private
and public members, static data and function members, constructors
and their types, destructors, operator overloading, type conversion ,
friend functions.
16 Hrs
3
Continued…
UNIT-II
 Inheritance : Concept of Inheritance, types of inheritance:
single, multiple, multilevel, hierarchical, hybrid, protected
members, overriding, virtual base class.
 Polymorphism : Pointers in C++, Pointers and Objects, this
pointer, virtual and pure virtual functions, Implementing
polymorphism.
 I/O and File management : Concept of streams, cin and cout
objects, C++ stream classes, Unformatted and formatted I/O,
manipulators, File stream, C++ File stream classes, File
management functions, File modes, Binary and random files.
16 Hrs
4
Continued…
UNIT-III
 Templates, Exceptions and STL:What is template? function
templates and class templates, Introduction to exception, try-
catch-throw, multiple catch, catch all, rethrowing exception,
implementing user defined exceptions, Overview and use of
Standard Template Library.
7 Hrs
TEXT BOOK:
 T1. E Balagurusamy, “Object Oriented Programming With C++”,
TMH , Third Edition.

 REFERENCE BOOKS:
 R1. Robert Lafore, “Object Oriented Programming in Turbo C++”,
Galgotia publishers.
 R2. Bjarne Stroustrup , “Programming Principles and Practice Using
C++”, Addison-Wesley.
5
NPTEL/ MOOC Link:
 https://ocw.mit.edu/courses/electrical-engineering-and-
computer-science/6-096-introduction-to-c-january-iap-
2011/
 https://www.coursera.org/learn/c-plus-plus-a
 https://www.coursera.org/learn/c-plus-plus-b

6
What is C++ ??
◼ C++ is a compiled, object-oriented language
◼ It is the “successor” to C, a procedural language
◼ (the “++” is called the successor operator in C++)
◼ C was derived from a language called B which was
in turn derived from BCPL
◼ C was developed in the 1970’s by Dennis Ritchie of
AT&T Bell Labs
◼ C++ was developed in the early 1980’s by Bjarne
Stroustrup of AT&T Bell Labs.
7
Continued..
◼ C was standardized by American National
Standards Institute (ANSI) in 1989
◼ In 1990 International Standards
Organization (ISO) adopted the ANSI standard
◼ Most of C is a subset of C++

8
The Basics
 C++ is a statically typed, compiled, general-purpose, case-sensitive,
free-form programming language that supports procedural, object-
oriented, and generic programming.
 For a program to run, its source text has to be processed by a
compiler, producing object files, which are combined by a linker
yielding an executable program.
 A C++ program typically consists of many source code files (usually
simply called source files).

9
Basic Concepts of Object Oriented
Programming
 Objects
 Classes
 Data Abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

10
Getting started:
 Source code: File(s) that contains the C/C++
statements that provide program instructions
 Compiler: A software program that reads source
code and produces object or machine code, if the code
is “grammatically correct”
 Linker: Software program which links machine code
& library code to form an executable file
 Portable language: Language in which the source
code need not be changed when moved from one type
of computer to another
 A standardized language is portable language
11
Continued…
 Pointers: Variables that “point” to the other variable
 Operators: Symbols that direct certain operations to
be performed
 Functions: Discrete modules or units of code that
perform specific tasks
 C++ class: Fundamental unit in object-oriented
programming that contains the “job description” for a
program object

12
Procedure-oriented Programming
 Emphasis is on doing things (algorithms)
 Large programs are divided into smaller programs
known as functions
 Most of the functions share global data
 Data move openly around the system from function
to function
 Functions transform data from one form to
another
 Employs top-down approach in program design
13
 Example: C programming
Object-oriented Programming
 Program design based on the use of real world items
(objects) & the manner in which these objects interact
 Data structures are designed such that they characterize the
objects
 Functions that operate on the data of an object are tied
together in the data structure
 Data is hidden and cannot be accessed by external functions
 Objects may communicate with each other through
functions
 Follows bottom-up approach in program design
14 Example: C++, java
Benefits of OOP
• Through inheritance, we can eliminate redundant code extend the use of
existing classes.
• We can build programs from the standard working modules that
communicate with one another, rather than having to start writing the code
from scratch.
• The principle of data hiding helps the programmer to build secure program
that can not be invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any
interference.
• It is possible to map object in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more detail of
a model can implemental form.
• Object-oriented system can be easily upgraded from small to large system.
• Message passing techniques for communication between objects makes
to interface descriptions with external systems much simpler.
• Software complexity can be easily managed.
15
Application of OOP
• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems

16
General form of a C++ program
// Program description
#include directives
int main()
{
constant declarations
variable declarations
executable statements
return 0;
}

17
Hello World! Program
//Hello World! Program
#include <iostream>

using namespace std; // make names from std visible without std::

int main()
{
cout << "Hello World!" << endl;
return 0;
}
 Hello World! is a first program in Kernighan and Ritchie’s The C
Programming Language
18
//Hello World! Program
#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
}

• "Hello, World!\n" is written onto the standard output


stream std::cout
• The std:: specifies that the name cout is to be found in the
standard-library namespace
• The semicolon is a statement terminator

19
C++ comments
 Comments are explanatory notes; they are ignored by the
compiler.
 There are two ways to include comments in a program:

// A double slash marks the start


of a //single line comment.

/* A slash followed by an asterisk


marks the start of a multiple line
comment. It ends with an asterisk
followed by a slash. */
20
C++ compiler directives
 The #include directive tells the compiler to include
some already existing C++ code in your program.
 The included file is then linked with the program.
 There are two forms of #include statements:
#include <iostream> //for pre-
defined files

#include "my_lib.h" //for user-


defined files
21
Example:
 #include <cmath> //used for sqrt() function
 #include <iostream> //used for cout to write
output to the screen
 #include <iomanip> //for output formatting
utilities

22
The using namespace std statement

 Namespace used to help organize the program


and avoid problems with program components
having the same name

23
Data types in C++
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
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t
24
Continued…
Several of the basic types can be modified using one
or more of these type modifiers:
 signed
 unsigned
 short
 long

25
Type Typical Bit Width Typical Range
char 1byte -128 to 127
unsigned char 1byte 0 to 255
signed char 1byte -128 to 127
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 2 bytes 0 to 65,535
long int 4bytes -2,147,483,647 to 2,147,483,647
float 4bytes Six digits of precision
double 8bytes Ten digits of precision
long double 10bytes Ten digits of precision
26 wchar_t 2 or 4 bytes 1 wide character
Variable Declaration in C++
 A variable provides us with named storage that the 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.
 Example:
int i, j, k;
char c, ch;
float f, salary;
double d;
27
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.
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,
28
Pointer, Array, Reference, Data structures and Classes.
C++ identifiers
 An identifier is a name for a variable, constant, function,
etc.
 It consists of a letter followed by any sequence of letters,
digits, and underscores.
 Examples of valid identifiers: First_name, age,
y2000, y2k
 Examples of invalid identifiers: 2000y
 Identifiers cannot have special characters in them. For
example: X=Y, J-20, ~Ricky,*Michael are
invalid identifiers.
 Identifiers are case-sensitive. For example: Hello,
hello, WHOAMI, WhoAmI, whoami are unique
identifiers.
29  Keywords cannot be included.
Local and Global variables

 Variables that are declared inside a function or


block are local variables.
 They can be used only by statements that are
inside that function or block of code.
 Local variables are not known to functions
outside their own.

30
Example
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
31
Global Variables:
 Global variables are defined outside of all the
functions, usually on top of the program.
 The global variables will hold their value
throughout the life-time of your program.
 A global variable can be accessed by any function.
 That is, a global variable is available for use
throughout your entire program after its
declaration.

32
#include <iostream>
using namespace std;
// Global variable declaration:
int g=50;
int main ()
{
int a, b; // Local variable declaration
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
33
Example
#include <iostream>
using namespace std; A program can have same
// Global variable declaration: name for local and global
int g = 20; variables but value of
local variable inside a
int main ()
function will take
{ preference
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
34
Defining Constants:
There are two simple ways in C++ to define constants:
 Using #define preprocessor.
Format: #define identifier value
 Using const keyword.
Format: const type variable = value;

35
Example:
#include <iostream> #include <iostream>
using namespace std; using namespace std;
#define LENGTH 10 int main()
#define WIDTH 5 {
#define NEWLINE '\n' const int LENGTH = 10;
int main() const int WIDTH = 5;
{ const char NEWLINE = '\n';
int area; int area;
area = LENGTH * WIDTH; area = LENGTH * WIDTH;
cout << area<< NEWLINE; cout << area<< NEWLINE;
return 0; return 0;
} }
36
Operators in C++
 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
o Arithmetic operators
o Relational operators
o Logical operators
o Bitwise operators
o Assignment operators
o Misc operators
37
Arithmetic Operators : Assume variable A
holds 10 and variable B holds 20, then

38
Relational Operators:
Assume variable A holds 10 and variable B holds 20, then:

39
40
Logical Operators:
Assume variable A holds 1 and variable B holds 0,
then:

41
Bitwise Operators:
Assume if A = 60; and B = 13; now in binary format they
will be as follows:
A = 0011 1100
B = 0000 1101

42
43
Assignment Operators:

44
45
Misc Operators

46
C++ Enumeration
 An enumeration is a user-defined type. Enumeration are defined
using keyword: enum.
Format: enum enum-name { list of names } var-list;
enum seasons { spring, summer, autumn, winter };
 This code is a enum declaration. After declaration, you can define
variable of type seasons.
 And this variable of type seasons can only have one of those 4 values
Ex: enum.cpp
 By default, the value of first enumerator is 0, second is 1 and so on. In
this program, spring is equal to 0, summer is equal to 1 and autumn is 2
and winter is 3.
 One very important thing to remember is that, spring, summer etc are
not variables. They are treated as integers by compiler. Hence, once
enumerators are defined, their value can't be changed in program.
47
Typecasting
 Typecasting is the concept of converting the value of one type into
another type.
 For example, you might have a float that you need to use in a
function that requires an integer.
Implicit conversion
 Almost every compiler makes use of what is called automatic
typecasting. It automatically converts one type into another type.
Explicit conversion
 If you want to do it manually, it can be done with what is called an
explicit conversion.
 Example: typecast.cpp

48
Operators Precedence in C++:
Priority Operator Type Operator Associativity
Highest Primary () [] . -> Left to right
Arithmetic */% Left to right
Arithmetic +- Left to right
Lowest Assignment = Right to left

49
C++ decision making statements
 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.

50
C++ if statement

Syntax:
if(boolean_expression)
{
/* statement(s) will execute if the
boolean expression is true*/
}

51
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 10;
// check the boolean condition
if( a < 20 )
{
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
52 }
C++ if...else statement
Syntax:
if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}
53
Flow Diagram:

54
Example:
cout << "a is less than 20;" <<
#include <iostream> endl; }
using namespace std; else
int main () {
{ /* if condition is false then print
// local variable declaration: the following */
int a = 100; cout << "a is not less than 20;"
// check the boolean condition << endl;
if( a < 20 ) }
{ cout << "value of a is : " << a <<
/* if condition is true then print endl;
the following */ return 0;
}
55
The if...else if...else Statement:
Syntax:
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
}
else
{
// executes when the none of the above condition is true.
56 }
C++ switch statement
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);
57 }
Flow Diagram:

58
The following rules apply to a switch statement:
 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
59
the default case.
C++ nested if statements
if( boolean_expression 1)
{
// Executes when the boolean expression 1 is true
if(boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
}

60
C++ Loop Types
 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.
 A loop statement allows us to execute a
statement or group of statements
multiple times
61
C++ while loop
 A while loop statement repeatedly executes a target statement
as long as a given condition is true.
Syntax:
The syntax of a while loop in C++ is:
while(condition)
{
statement(s);
}

62
Flow Diagram:

63
Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
64
C++ for loop
 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.
Syntax:
The syntax of a for loop in C++ is:
for ( init; condition; increment )
{
statement(s);
}

65
Flow Diagram:

66
Here is the flow of control in a for loop:
 The init 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 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
67 loop terminates.
Example:
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}
return 0;
}
68
C++ do...while loop
 Unlike for and while loops, which test the loop condition at
the top of the loop, the do...while loop checks its condition
at the bottom of the loop.
 A do...while loop is similar to a while loop, except that a
do...while loop is guaranteed to execute at least one time.
Syntax:
The syntax of a do...while loop in C++ is:
do
{
statement(s);
}while( condition );

69
Flow Diagram:

70
Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
71
C++ nested loops
Syntax:
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.
}

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

73
The syntax for a nested do...while loop statement in C++ is as
follows:

do
{
statement(s); // you can put more statements.
do
{
statement(s);
}while( condition );
}while( condition );

74
Loop Control Statements:
 Loop control statements change execution from
its normal sequence.
1. break statement: Terminates the loop or switch
statement and transfers execution to the statement
immediately following the loop or switch.
2. continue statement: Causes the loop to skip the
remainder of its body and immediately retest its condition
prior to reiterating.
3. goto statement: Transfers control to the labeled
statement. Though it is not advised to use goto statement in
your program.
75
C++ break statement
The break statement has the following two usages
in C++:
 When the break statement is encountered inside a
loop, the loop is immediately terminated and
program control resumes at the next statement
following the loop.
 It can be used to terminate a case in the switch
statement
 Syntax: break;
 Example: break.cpp
76
C++ continue statement
 The continue statement works somewhat like
the break statement.
 Instead of forcing termination, however, continue
forces the next iteration of the loop to take place,
skipping any code in between.
 Syntax: continue;
 Example: continue.cpp

77
C++ goto statement
 A goto statement provides an unconditional jump from
the goto to a labeled statement in the same function.
 Syntax:
The syntax of a goto statement in C++ is:
goto label;
..
.
label: statement;
 Example: goto.cpp

78
C++ Functions
 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.
 The division usually is such that each function performs
a specific task.
 A function declaration tells the compiler about a
function's name, return type, and parameters.
79
Continued…
 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
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.
80
Defining a Function:
The general form of a C++ function definition is as follows:

return_type function_name( parameter list )


{
body of the function
}

81
 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.
82
Example:
// 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;
}
83
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_type function_name( parameter list );
 For the above defined function max(), following is the function
declaration:
int max(int num1, int num2);
 Parameter names are not important in function declaration
only their type is required, so following is also valid
declaration:
84 int max(int, int);
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.
 Example: Function.cpp
85
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.

86
87
C++ function call by value
 The call by value method of passing arguments to a
function copies the actual value of an argument into
the formal parameter of the function.
 In this case, changes made to the parameter inside the
function have no effect on 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.
 Example: call_by_value1.cpp
88
C++ function call by pointer
 The call by pointer method of passing arguments to a function
copies the address of an argument into the 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 passed
argument.
 To pass the value by pointer, argument pointers are passed to the
functions just like any other value.
 So accordingly you need to declare the function parameters as
pointer types as in the following function swap(), which
exchanges the values of the two integer variables pointed to by its
arguments.

89
Example: call_by_pointer.cpp
C++ function call by reference
 The call by reference method of passing arguments to a function
copies the reference of an argument into 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 passed
argument.
 To pass the value by reference, argument reference is passed to the
functions just like any other value.
 So accordingly you need to declare the function parameters as
reference types as in the following function swap(), which
exchanges the values of the two integer variables pointed to by its
arguments.
 Example: call_by_reference
90
Return by reference
 A reference can also be returned by the function.
 A function that returns reference variable is in fact an alias for
referred variable.
 When a variable is returned by reference, a reference to the
variable is passed back to the caller.
 The caller can then use this reference to continue modifying
the variable, which can be useful at times.
 Return by reference is also fast, which can be useful when
returning structs and classes.
 Example: Return_reference.cpp

91
C++ inline function
 If a function is inline, the compiler places a copy of the code of that
function at each point where the function is called at compile time.
 To inline a function, place the keyword inline before the function
name and define the function before any calls are made to the function.
Advantage
 Less overhead and faster program execution as there is no transfer of
control from the main program to the function definition whenever
function call is encountered.
Disadvantage:
 program needs more memory space as function definitions are copied
at multiple places in the program wherever the function call is
encountered.
 Example: Inline.cpp
92
Function Overloading
 Function overloading (also method overloading) is a
programming concept that allows programmers to define
two or more functions with the same name and in the
same scope.
 In function overloading, the function is redefined by
using either different types of arguments or a different
number of arguments.
 Function overloading can be considered as an example
of polymorphism(Compile time) feature in C++.
 Example: Function_overloading.cpp
93
Default Arguments in C++
 In computer programming, a default argument is an
argument to a function that a programmer is not required to
specify.
 The default arguments are used when there is no arguments
or only few arguments while calling a function.
 The default arguments are used during compilation of
program.
 Example: Default _arguements.cpp

94
Classes and objects
 “A class is a way to bind the data and its associated
function together”
 Object is an instance of class
 Example: Class.cpp
Class_001.cpp

95
Access Specifiers in C++
 Access specifiers in C++ define how the members of the class
can be accessed (data hiding).
 Access Modifiers or Access Specifiers in a class are used to set the
accessibility of the class members. That is, it sets some restrictions
on the class members not to get directly accessed by the outside
functions.
 There are 3 types of access modifiers available in C++:
 Public
 Private
 Protected
 Public: 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.
96
 Private: The class members declared as private can be accessed only
by the functions inside the class. They are not allowed to be accessed
directly by any object or function outside the class.
 Protected: Protected access modifier is similar to that of private
access modifiers, the difference is that the class member declared as
Protected are inaccessible outside the class but they can be accessed
by any subclass(derived class) of that class.

97
Static Data Member
 It is generally used to store value common to the whole class. The
static data member differs from an ordinary data
member in the following ways :
a) It is initialized to zero when the first object of its class is created.
b) Only a single copy of the static data member is used by all the
objects.
c) It can be used within the class but its lifetime is the whole
program.
 For making a data member static, we require :
(a) Declare it within the class.
(b) Define it outside the class.
Example: Static_data.cpp
98
Static Member Function:
 A static member function can access only the static members
of a class.
 A static member function differs from the other member
functions in the following ways:
(i) Only static members (functions or variables) of the same
class can be accessed by a static member function.
(ii) It is called by using the name of the class rather than an
object as given below:
Name_of_the_class :: function_name
 Example: Static_function.cpp

99
Constructors in C++
 A constructor is a member function of a class which initializes objects of a
class.
 In C++, Constructor is automatically called when object(instance of class)
create. It is special member function of the class.
 A constructor is different from normal functions in following ways:
 Constructor has same name as the class itself
 Constructors don’t have return type
 A constructor is automatically called when an object is created.
Types of Constructors
 Default Constructors: Default constructor is the constructor which
doesn’t take any argument. It has no parameters.
 Parameterized Constructors: It is possible to pass arguments to
constructors. Typically, these arguments help initialize an object when it is
created.
100
 Example: Default_constuctor.cpp
 Copy Constructor: A copy constructor is a member function
which initializes an object using another object of the same class.
 A copy constructor has the following general function prototype:
ClassName (ClassName &old_obj);
 Example: Copy_constructor.cpp

Uses of Parameterized constructor:


 It is used to initialize the various data elements of different objects
with different values when they are created.
 It is used to overload constructors.
 Example: Overloaded_construct.cpp

101
Destructors in C++
 C++ destructor is a special member function that is executed
automatically when an object is destroyed that has been created by
the constructor.
 C++ destructors are used to de-allocate the memory that has
been allocated for the object by the constructor.
 A destructor function is called automatically when the object goes
out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
 Example: Destructor.cpp

102
Friend function in C++
 A friend function of a class is defined outside that class' scope but
it has the right to access all private and protected members of the
class.
 Even though the prototypes for friend functions appear in the
class definition, friend is not a member functions.
 A friend function can be:
a) A method of another class
b) A global function
 Example: Friend.cpp
Friend_other_class.cpp

103
 Following are some important points about friend
functions and classes:
1) Friends should be used only for limited purpose.
too many functions or external classes are declared as
friends of a class with protected or private data, it
lessens the value of encapsulation of separate classes in
object-oriented programming.
 2) Friendship is not mutual. If class A is a friend of B,
then B doesn’t become a friend of A automatically.
 3) Friendship is not inherited.

104
Operator Overloading
 Operator overloading is a flexible option for the creation of new
definitions for most of C++ operators.
 The general form of operator function is:
 Syntax:
Return_type class_name:: operator op(arglist)
{
Function body //task defined
}
 Operators that cannot be overloaded
1. Class member access operators(. , .*)
2. Scope resolution operator(::)
3. Size operator(sizeof)
105 4. Conditional operator(?)
 Example: Overloading_unary_op.cpp
 Example: Overloading_unary_op_Friend.cpp
 Example: Overloading_bin_op.cpp
 Example: Overloading_bin_op_Friend.cpp

106
Type Conversions
 Three types of situations might arise for data conversion between
different types :
(i) Conversion form basic type to class type.
(ii) Conversion from class type to basic type.
(iii) Conversion from one class type to another class type.
 Example: basic_class1.cpp
 Example: basic_class2.cpp
 Example: class_basic.cpp
 Example: class_class.cpp

107
C++ Pointers
 C++ pointers are easy and fun to learn.
 Some C++ tasks are performed more easily with
pointers.
 Other C++ tasks, such as dynamic memory
allocation, cannot be performed without them.
 Every variable has a memory location and every
memory location has its address defined which can be
accessed using ampersand (&) operator which denotes
an address in memory.
 Example: ampersand.cpp
108
What Are Pointers?
 A pointer is a variable whose value is the address of another
variable.
 Like any variable or constant, you must declare a pointer before
you can work with it.
 The general form of a pointer variable declaration is:
type *var-name;
 Here, type is the pointer's base type; it must be a valid C++
type and var-name is the name of the pointer variable.
 The asterisk you used to declare a pointer is the same asterisk
that you use for multiplication.
 However, in this statement the asterisk is being used to
109
designate a variable as a pointer.
Continued…
 Following are the valid pointer declaration:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
 The actual data type of the value of all pointers, whether
integer, float, character, or otherwise, is the same, a long
hexadecimal number that represents a memory address.
 The only difference between pointers of different data types
is the data type of the variable or constant that the pointer
points to.
110
Using Pointers in C++:
 There are few important operations, which we will
do with the pointers very frequently.
a) we define a pointer variables
b) assign the address of a variable to a pointer and
c) finally access the value at the address available in the
pointer variable.
 This is done by using unary operator * that returns
the value of the variable located at the address
specified by its operand.
 Example: pointer.cpp
111
C++ Pointers in Detail:

112
C++ NULL pointers
 It is always a good practice to assign the pointer NULL
to a pointer variable in case you do not have exact
address to be assigned.
 This is done at the time of variable declaration.
 A pointer that is assigned NULL is called a null pointer.
 The NULL pointer is a constant with a value of zero
defined in several standard libraries, including iostream.
 If a pointer contains the null (zero) value, it is assumed
to point to nothing.
 Example: null_pointer.cpp
113
C++ pointer arithmetic
 We can perform arithmetic operations on a pointer just as
we can a numeric value.
 There are four arithmetic operators that can be used on
pointers: ++, --, +, and –

Incrementing a Pointer:
 We prefer using a pointer in our program instead of an
array because the variable pointer can be incremented,
unlike the array name which cannot be incremented
because it is a constant pointer.
 Example: ptr_arith_inc.cpp
114
Continued…
Decrementing a Pointer:
 The same considerations apply to decrementing a pointer,
which decreases its value by the number of bytes of its data
type.
 Example: ptr_arith_dec.cpp

Pointer Comparisons
 Pointers may be compared by using relational operators,
such as ==, <, and >. If p1 and p2 point to variables that are
related to each other, such as elements of the same array,
then p1 and p2 can be meaningfully compared.
115 Example: ptr_comparison.cpp
C++ array of pointers
 There may be a situation, when we want to maintain an array,
which can store pointers to an int or char or any other data
type available.
 Following is the declaration of an array of pointers to an
integer:
int *ptr[MAX];
 This declares ptr as an array of MAX integer pointers. Thus,
each element in ptr, now holds a pointer to an int value.
Example:
1. array_of_ptr.cpp
2. array_of_ptr1.cpp
116
C++ Pointer to Pointer (Multiple Indirection)

 A pointer to a pointer is a form of multiple indirection or a


chain of pointers.
 A variable that is a pointer to a pointer must be declared as
such.
 This is done by placing an additional asterisk in front of its
name. For example: int **var;
 Example: ptr_to_ptr.cpp
117
Passing pointers to functions in C++
 C++ allows you to pass a pointer to a function.
 To do so, simply declare the function parameter as a pointer
type.
 Example: ptr_to_functn.cpp

118
Return pointer from functions in C++
 C++ allows to return a pointer from a function.
 To do so, we would have to declare a function returning a
pointer as in the following example:
int * myFunction()
{
.
.
.
}
Example: return_pointer.cpp
119
C++ References
 A reference variable is an alias, that is, another name for an
already existing variable.
 Once a reference is initialized with a variable, either the variable
name or the reference name may be used to refer to the variable.
C++ References vs Pointers:
 You cannot have NULL references.You must always be able to
assume that a reference is connected to a legitimate piece of
storage.
 Once a reference is initialized to an object, it cannot be changed
to refer to another object. Pointers can be pointed to another
object at any time.
 A reference must be initialized when it is created. Pointers can be
initialized at any time.
120
Creating References in C++:
 Think of a variable name as a label attached to the variable's
location in memory.
 You can then think of a reference as a second label attached
to that memory location.
 Therefore, you can access the contents of the variable
through either the original variable name or the reference.
For example, suppose we have the following example:
int i = 17;
 We can declare reference variables for i as follows.
int& r = i;
121
Example: reference.cpp
 References are usually used for function argument lists and
function return values.
 So following are two important subjects related to C++
references:

 Example: (1) refer_parameter.cpp


(2) refer_return.cpp
122
123

You might also like