0% found this document useful (0 votes)
47 views

CPP Module 1 New

Object oriented programming (OOP) is an approach that aims to eliminate some flaws of procedural programming. OOP focuses on data rather than procedures, divides programs into objects that encapsulate both data and functions, and allows for inheritance and polymorphism. Some key concepts of OOP include objects, classes, encapsulation, inheritance, and polymorphism. Classes group similar objects and define attributes and methods that operate on the attributes. Encapsulation wraps data and functions together into classes and protects data from direct access. Inheritance allows new classes to inherit attributes and behaviors from existing classes. Polymorphism allows the same operations to behave differently based on the types of objects.

Uploaded by

A 18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

CPP Module 1 New

Object oriented programming (OOP) is an approach that aims to eliminate some flaws of procedural programming. OOP focuses on data rather than procedures, divides programs into objects that encapsulate both data and functions, and allows for inheritance and polymorphism. Some key concepts of OOP include objects, classes, encapsulation, inheritance, and polymorphism. Classes group similar objects and define attributes and methods that operate on the attributes. Encapsulation wraps data and functions together into classes and protects data from direct access. Inheritance allows new classes to inherit attributes and behaviors from existing classes. Polymorphism allows the same operations to behave differently based on the types of objects.

Uploaded by

A 18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

MODULE I-

Unit 1: (10 hrs.) Principles of Object Oriented Programming, Beginning with C++ Procedure
Oriented Programming-Object Oriented Programming-Basic concepts of object-oriented
programming- Benefits of OOP- Applications of OOP-A simple C++program-Structure of C++
program C++ data types- Symbolic constants- Reference by variables-Operators in C++- Operator
precedence Control structures- Function in C++ - The main function, Function prototyping- Call by
reference- Return by reference- Inline function- Default arguments- Function overloading.

Procedure-Oriented Programming
In the procedure oriented approach, the problem is viewed as the sequence of things to be
done such as reading, calculating and printing such as cobol, fortran and c. The primary
focus is on functions. The technique of hierarchical decomposition has been used to specify
the tasks to be completed for solving a problem

Procedure oriented programming basically consists of writing a list of instructions for the
computer to follow, and organizing these instructions into groups known as functions

In a multi-function program, many important data items are placed as global so that they
may be accessed by all the functions. Each function may have its own local data

Some Characteristics exhibited by procedure-oriented programming are:


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

Drawbacks of procedure-oriented programming are:

1
1. Unrestricted Access (for Global variables)
Global data are more vulnerable to an inadvertent change by a function. In a large
program it is very difficult to identify what data is used by which function. In case we
need to revise an external data structure, we also need to revise all functions that access
the data. This provides an opportunity for bugs to creep in.

2. This approach does not model real world problems

Another serious drawback with the procedural approach is that we do not model
real world problems very well. This is because functions are action-oriented and do not
really corresponding to the element of the problem.

Object Oriented Programming

Object Oriented Programming (OOP) is an approach to program organization and


development that attempts to eliminate some of the pitfalls of conventional
programming methods by incorporating the best of structured programming features
with several powerful new concepts. It is a new way of organizing and developing
programs and has nothing to do with any particular language.

The major motivating factor in the invention of object-oriented approach is to


remove some of the flaws encountered in the procedural approach. OOP treats data as a
critical element in the program development and does not allow it to flow freely around
the system. It ties data more closely to the function that operate on it, and protects it
from accidental modification from outside function. OOP allows decomposition of a
problem into a number of entities called objects and then builds data and function
around these objects. The data of an object can be accessed only by the function
associated with that object. However, function of one object can access the function of
other objects

Some of the features of object oriented programming are:


• Emphasis is on data rather than procedure.

2
• Programs are divided into what are known as objects.
• Data structures are designed such that they characterize the objects.
• Functions that operate on the data of an object are ties together in the data structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.
Basic Concepts of Object Oriented Programming

It is necessary to understand some of the concepts used extensively in object-oriented


programming. These include:
1. Objects
2. Classes
3. Data abstraction and encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing

1. Objects
Objects are the basic run time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program
has to handle. They may also represent user-defined data such as vectors, time and lists.
Programming problem is analyzed in term of objects and the nature of communication
between them. Program objects should be chosen such that they match closely with the
real-world objects. Objects take up space in the memory and have an associated address
like a record in Pascal, or a structure in c.
When a program is executed, the objects interact by sending messages to one
another. For example, if “customer” and “account” are to object in a program, then the
customer object may send a message to the count object requesting for the bank balance.
Each object contain data, and code to manipulate data. Objects can interact without having
to know details of each other’s data or code. It is a sufficient to know the type of message
accepted, and the type of response returned by the objects.

2. Classes

3
Objects contain data, and code to manipulate that data. The entire set of data and
code of an object can be made a user-defined data type with the help of class. In fact,
objects are variables of the type class. Once a class has been defined, we can create any
number of objects belonging to that class. Each object is associated with the data of type
class with which they are created. A class is thus a collection of objects similar types. For
examples, Mango, Apple and orange members of class fruit. Classes are user-defined that
types and behave like the built-in types of a programming language. The syntax used to
create an object is not different then the syntax used to create an integer object in C. If fruit
has been defines as a class, then the statement Fruit Mango;
Will create an object mango belonging to the class fruit.
Since the classes use the concept of data abstraction, they are known as Abstract
Data Types (ADT).

3. Data Abstraction and Encapsulation


The wrapping up of data and function into a single unit (called class) is known as
encapsulation. Data and encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are wrapped in the class can
access it. These functions provide the interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding or
information hiding.
Abstraction refers to the act of representing essential features without including the
background details or explanation. Classes use the concept of abstraction and are defined as
a list of abstract attributes such as size, wait, and cost, and function operate on these
attributes. They encapsulate all the essential properties of the object that are to be created.
The attributes are some time called data members because they hold information. The
functions that operate on these data are sometimes called methods or member function.

4. Inheritance
Inheritance is the process by which objects of one class acquired the properties of
objects of another classes. It supports the concept of hierarchical classification. For
example, the bird, ‘robin’ is a part of class ‘flying bird’ which is again a part of the class
‘bird’. The principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated

In OOP, the concept of inheritance provides the idea of reusability. This means that we can
add additional features to an existing class without modifying it. This is possible by deriving

4
a new class from the existing one. The new class will have the combined feature of both the
classes. The real appeal and power of the inheritance mechanism is that it allows the
programmer to reuse a class i.e almost, but not exactly, what he wants, and to tailor the
class in such a way that it does not introduced any undesirable side-effects into the rest of
classes.

5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term,
means the ability to take more than on form. An operation may exhibit different behavior is
different instances. The behavior depends upon the types of data used in the operation. For
example, consider the operation of addition. For two numbers, the operation will generate a
sum. If the operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Also a single function name can be used to handle different number and different
types of argument. This is something similar to a particular word having several different
meanings depending upon the context. Using a single function name to perform different
type of task is known as function overloading.
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of
operations may be accessed in the same manner even though specific action associated
with each operation may differ. Polymorphism is extensively used in implementing
inheritance.

6. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance. A function call associated with a polymorphic reference
depends on the dynamic type of that reference.

7. Message Passing
An object-oriented program consists of a set of objects that communicate with each other.
The process of programming in an object-oriented language, involves the following basic
steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another. The concept of message passing makes
it easier to talk about building systems that directly model or simulate their real-world
counterparts.
A Message for an object is a request for execution of a procedure, and therefore will invoke
a function (procedure) in the receiving object that generates the desired results. Message

5
passing involves specifying the name of object, the name of the function (message) and the
information to be sent. Example: Employee. Salary (name);
Here Employee is the Object,Salary is the message and Name is the information

Object has a life cycle. They can be created and destroyed. Communication with an
object is feasible as long as it is alive.

Benefits of OOP
1. Through inheritance, we can eliminate redundant code extend the use of existing
Classes.
2. 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.
3. It is possible to have multiple instances of an object to co-exist without any
interference.
4. It is possible to map object in the problem domain to those in the program.
5. It is easy to partition the work in a project based on objects.
6. The data-centered design approach enables us to capture more detail of a model can
implemental form.
7. Object-oriented system can be easily upgraded from small to large system.
8. Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
9. Software complexity can be easily managed

Applications of OOP
The promising areas of application of OOP include:
1. Real-time system
2. Simulation and modeling
3. Object-oriented data bases
4. Hypertext, Hypermedia, and expertext
5. AI and expert systems
6. Neural networks and parallel programming
7. Decision support and office automation systems
8. CIM/CAM/CAD systems

Introduction of C++
C++ is an object-oriented programming language. It was developed by Bjarne
Stroustrup at AT&T Bell Laboratories in Murray Hill, New Jersey, USA, in the early 1980’s.
Stroustrup, an admirer of Simula67 and a strong supporter of C, wanted to combine the best
of both the languages and create a more powerful language that could support object-
oriented programming features and still retain the power and elegance of C. The result was
C++. Therefore, C++ is an extension of C with a major addition of the class construct feature
of Simula67. Since the class was a major addition to the original C language, Stroustrup
initially called the new language ‘C with classes’. However, later in 1983, the name was
changed to C++. The idea of C++ comes from the C increment operator ++, thereby
suggesting that C++ is an augmented version of C.

6
C+ + is a superset of C. Almost all c programs are also C++ programs. However, there
are a few minor differences that will prevent a c program to run under C++ complier. We
shall see these differences later as and when they are encountered.
The most important facilities that C++ adds on to C are classes, inheritance, function
overloading and operator overloading. These features enable creating of abstract data
types, inherit properties from existing data types and support polymorphism, thereby
making C++ a truly object-oriented language.

Application of C++
C++ is a versatile language for handling very large programs; it is suitable for virtually any
programming task including development of editors, compilers, databases, communication
systems and any complex real life applications systems.
• Since C++ allow us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
• While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
• C++ programs are easily maintainable and expandable. When a new feature needs to
be implemented, it is very easy to add to the existing structure of an object.
• It is expected that C++ will replace C as a general-purpose language in the near future.

Comments
C++ introduces a new comment symbol // (double slash). Comment start with a double slash
symbol and terminate at the end of the line. A comment may start anywhere in the line, and
whatever follows till the end of the line is ignored. Note that there is no closing symbol.
The double slash comment is basically a single line comment.
The C comment symbols /*,*/ are still valid and are more suitable for multiline
comments.
 supports single line and multi-line comments.
 All characters available inside any comment are ignored by C++ compiler.
 Block comments start with /* and end with */
 Line comments start with //,extending to the end of the line
eg:-
// This is a single line comment
/* C++ comments can also
* span multiple lines
*/

Header Files
The #include directive instructs the compiler to include the contents of the file
enclosed within angular brackets into the source file.
 a header file sometimes known as an include file.
 Header files almost always have a .h extension.
 The purpose of a header file is to hold declarations for other files or functions to
use.
 Examples :- iostream.h, conio.h , string.h, stdio.h, etc….
iostream. h - input output stream. iostream.h is used for input output functions .
( cout , cin) .

7
conio. h - concatenated input output . conio.h includes the declarations of getch,
getc, putc, clrscr, etc.
string. h - used for string handling functions such as strcpy, strlen strrev, strcpy etc….

OOPs approach is based on the concept of client-server model. The class definition including
the member functions constitute the server that provides services to the main program
known as client. The client uses the server through the public interface of the class.

The main( ) function


In C++, main () returns an integer value to the operating system. Therefore, every main () in
C++ should end with a return (0) statement; otherwise a warning an error might occur. Since
main () returns an integer type for main () is explicitly specified as int. Note that the default
return type for all function in C++ is int.

int main ()
• This line corresponds to the beginning of the definition of the main function.

8
• The main function is the point by where all C++ programs start their execution,
independently of its location within the source code.
• It does not matter whether there are other functions with other names defined
before or after it – the instructions contained within this function's definition will
always be the first ones to be executed in any C++ program. For that same reason, it
is essential that all C++ programs have a main function.
• The word main is followed in the code by a pair of parenthesis (()). That is because it
is a function declaration:
• Right after these parentheses we can find the body of the main function
enclosed in braces ({}). What is contained within these braces is what the
function does when it is executed.

Output operator
The statement cout causes the string in quotation marks to be displayed on the
screen. This statement introduces two new C++ features, cout and <<. The identifier
cout(pronounced as C out) is a predefined object that represents the standard output
stream in C++. Here, the standard output stream represents the screen. It is also
possible to redirect the output to other output devices. The operator << is called the
insertion or put to operator.
example:- cout<<”C++ is better than C.”;

Input Operator
The statement cin >> number1;
>> is an input statement and causes the program to wait for the user to type in a number.
The number keyed in is placed in the variable number1. The identifier cin (pronounced ‘C
in’) is a predefined object in C++ that corresponds to the standard input stream. Here, this
stream represents the keyboard.
The operator >> is known as extraction or get from operator. It extracts (or takes) the value
from the keyboard and assigns it to the variable on its right. This corresponds to a familiar
scanf() operation. Like <<, the operator >> can also be overloaded.

9
Cascading of I/O Operators

Multiple use of << or >> in one statement is called cascading. eg:-


cout << “Sum = ” << sum << “\n” ;
cin >> num1 >> num2 ;

Tokens
The smallest individual units in a program are known as tokens.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Operators and special characters

1. Keywords
Keywords are the reserved words used in C++. We cannot use the keywords as variables.
Eg :- public, while, void, friend, if, int …etc.

2.Identifiers (variables)
A variable is used to store values in the program.A valid identifier is a sequence of one
or more letters, digits or underscore characters (_).
eg :- int A, B, C ;

Rules for valid identifiers


1. A valid identifier is a sequence of one or more letters, digits or underscore characters
(_).
2. Neither spaces nor punctuation marks or symbols can be part of an identifier.
3. Only letters, digits and single underscore characters are valid.
4. Variable identifiers should begin with an underscore character (_ ) or a letter

Initialization of variables
There are two ways to initialize variables in C++:
type identifier = initial_value ;
For example:
int a = 0;

10
type identifier (initial_value) ;
For example:
int a (0);
This way to initialize variables, known as constructor initialization, is done by enclosing
the initial value between parentheses (()):

3. Constants
Constants have fixed value. Constants, like variables, contain data type.

Defining Constants:
There are two simple ways in C++ to define constants:
 Using #define preprocessor.
 Using const keyword.

The #define Preprocessor:


Following is the form to use #define preprocessor to define a constant:
#define identifier value
eg: #define LENGTH 10

The const Keyword:


You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
eg: const int LENGTH = 10;

4. Strings
Strings in C++ are classified as Character String and String Class

4.1 Character String:


This string is actually a one-dimensional array of characters which is terminated by a null
character '\0'. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as
follows:
char greeting[] = "Hello";
Following is the memory presentation of above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant. The C++
compiler automatically places the '\0' at the end of the string when it initializes the array.
C++ supports a wide range of functions that manipulate null-terminated strings:
Function & Purpose
strcpy(s1, s2);
Copies string s2 into string s1.

11
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
4.2 String Class
The standard C++ library provides a string class type that supports all the operations
mentioned above, additionally much more functionality.

5. Operators and special characters


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 following type of
operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

Arithmetic Operators:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by de-numerator B / A will give 2
Modulus Operator and remainder of
% B % A will give 0
after an integer division
Increment operator, increases integer
++ A++ will give 11
value by one
Decrement operator, decreases integer
-- A-- will give 9
value by one
Relational Operators:

Operator Description Example


Checks if the value of two operands is
== equal or not, if yes then condition (A == B) is not true.
becomes true.
!= Checks if the value of two operands is (A != B) is true.

12
equal or not, if values are not equal
then condition becomes true.
Checks if the value of left operand is
> greater than the value of right operand, (A > B) is not true.
if yes then condition becomes true.
Checks if the value of left operand is
< less than the value of right operand, if (A < B) is true.
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
>= (A >= B) is not true.
right operand, if yes then condition
becomes true.
Checks if the value of left operand is
less than or equal to the value of right
<= (A <= B) is true.
operand, if yes then condition becomes
true.
Logical Operators:

Operator Description Example


Called Logical AND operator. If both the
&& operands are non zero then condition (A && B) is false.
becomes true.
Called Logical OR Operator. If any of the
|| two operands is non zero then (A || B) is true.
condition becomes true.
Called Logical NOT Operator. Use to
reverses the logical state of its operand.
! !(A && B) is true.
If a condition is true then Logical NOT
operator will make false.
Bitwise Operators:

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

Operator Description Example


Binary AND Operator copies a bit to the
& (A & B) will give 12 which is 0000 1100
result if it exists in both operands.
Binary OR Operator copies a bit if it
| (A | B) will give 61 which is 0011 1101
exists in either operand.
Binary XOR Operator copies the bit if it
^ (A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.
Binary Ones Complement Operator is
~ unary and has the effect of 'flipping' (~A ) will give -60 which is 1100 0011
bits.
<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111 0000
operands value is moved left by the

13
number of bits specified by the right
operand.
Binary Right Shift Operator. The left
operands value is moved right by the
>> A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.
Assignment Operators:

Operator Description Example


Simple assignment operator, Assigns
= values from right side operands to left C = A + B will assign value of A + B into C
side operand
Add AND assignment operator, It adds
+= right operand to the left operand and C += A is equivalent to C = C + A
assign the result to left operand
Subtract AND assignment operator, It
subtracts right operand from the left
-= C -= A is equivalent to C = C - A
operand and assign the result to left
operand
Multiply AND assignment operator, It
multiplies right operand with the left
*= C *= A is equivalent to C = C * A
operand and assign the result to left
operand
Divide AND assignment operator, It
divides left operand with the right
/= C /= A is equivalent to C = C / A
operand and assign the result to left
operand
Modulus AND assignment operator, It
%= takes modulus using two operands and C %= A is equivalent to C = C % A
assign the result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
bitwise exclusive OR and assignment
^= C ^= 2 is same as C = C ^ 2
operator
bitwise inclusive OR and assignment
|= C |= 2 is same as C = C | 2
operator
Misc Operators

There are few other operators supported by C++ Language.

Operator Description
sizeof operator returns the size of a variable. For example
Sizeof
sizeof(a), where a is integer, will return 4.
Conditional operator. If Condition is true ? then it returns value
Condition ? X : Y
X : otherwise value Y

14
Comma operator causes a sequence of operations to be
, performed. The value of the entire comma expression is the
value of the last expression of the comma-separated list.
Member operators are used to reference individual members of
. (dot) and -> (arrow)
classes, structures, and unions.
Casting operators convert one data type to another. For
Cast
example, int(2.2000) would return 2.
Pointer operator & returns the address of an variable. For
&
example &a; will give actual address of the variable.
Pointer operator * is pointer to a variable. For example *var;
*
will pointer to a variable var.
Operators Precedence in C++:

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

C++ Variable Scope:

A scope is a region of the program and there are three places where variables can be
declared:
1. Inside a function or a block which is called local variables,
2. In the definition of function parameters which is called formal parameters.
3. Outside of all functions(in the main body of the source code) which is called global
variables.

Local 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. Following is the example using local variables:

15
#include <iostream.h>
int main ()
{
// Local variable declaration:
int a, b;
int c;

// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
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 lifetime 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. Following is the example using global
and local variables:

#include <iostream>
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}

 Global variables can be referred from anywhere in the code, even inside functions,
whenever it is after its declaration.
 The scope of local variables is limited to the block enclosed in braces ({}) where they
are declared
Initializing Local and Global Variables:

When a local variable is defined, it is not initalised by the system, you must initalise it
yourself. Global variables are initalised automatically by the system when you define them

C++ DATA TYPES

16
1. Built-in Data Types

ANSI C++ added two more data types

17
 bool
 wchar_t

Two normal use of void:


o To specify the return type of a function when it is not returning any value.
o To indicate an empty argument list to a function.
eg:- void function-name ( void )

2. Derived data types


Derived data types are derived from basic data type. A derived data type must contain
a basic data type. Eg :- int *p, int a [10], float B [25] ; Array, Function and Pointer are
derived data types

2.1 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 can define additional functions.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function.
The C++ standard library provides numerous built-in functions that your program can call.
For example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function:
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:

 Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument.
The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define

Example:-// function returning the max between two numbers


int max(int num1, int num2)
{

18
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main
program.
To call a function you simply need to pass the required parameters along with function
name and if function returns a value then you can store returned value. For example:
#include <iostream.h>

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

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

// calling a function to get max value.


ret = max(a, b);

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

return 0;
}

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

19
}
Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
Call by value
the parameter inside the function have no effect on the
argument.
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
Call by pointer
actual argument used in the call. This means that changes made
to the parameter affect the argument.
This method copies the reference of an argument into the
formal parameter. Inside the function, the reference is used to
Call by reference
access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code within
a function cannot alter the arguments used to call the function and above mentioned
example while calling max() function used the same method.

Benefits:-
1. top-down - structured programming
2. to reduce length of the program
3. reusability
4. function over-loading
Arrays

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

20
This is called a single-dimension array. The arraySize must be an integer constant
greater than zero and type can be any valid C++ data type. For example, to declare a 10-
element array called balance of type double, use this statement:

double balance[10];
Initializing Arrays:

You can initialize C++ array elements either one by one or using a single statement as
follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements
that we declare for the array between square brackets [ ]. Following is an example to
assign a single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array
with 4th index will be 5th ie. last element because all arrays have 0 as the index of their
first element which is also called base index. Following is the pictorial representaion of
the same array we discussed above:

Accessing Array Elements:

An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to
salary variable.
Multi Dimensional Arrays
C++ allows multidimensional arrays. Here is the general form of a multidimensional array
declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer
array:
int threedim[5][10][4];
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size x,y you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

21
A two dimensional array can be think as a table which will have x number of rows and y
number of columns. A 2-dimentional array a which contains three rows and four
columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ],


where a is the name of the array, and i and j are the subscripts that uniquely identify
each element in a.
Initializing Two-Dimensional Arrays:
Multidimensioned arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following
initialization is equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements:
An element in 2-dimensional array is accessed by using the subscripts ie. row index and
column index of the array. For example:
int val = a[2][3];

User-Defined Data Types


1. Structures
C/C++ arrays allow you to define variables that combine several data items of the same kind
but structure is another user defined data type which allows you to combine data items of
different kinds.
Defining a Structure:
To define a structure, you must use the struct statement. The struct statement defines a
new data type, with more than one member, for your program. The format of the struct
statement is this:

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

22
The structure tag is optional and each member definition is a normal variable definition,
such as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it
is optional. Here is the way you would declare the Book structure:

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
}book;
Structure is different from an array in the sense that an array represents an aggregate of
elements of same type whereas a structure represents an aggregate of elements of arbitrary
types..

2. Union
Unions allow one same portion of memory to be accessed as different data types, since
all of them are in fact the same location in memory. Its declaration and use is similar to the
one of structures but its functionality is totally different:union union_name { member_type1
member_name1; member_type2 member_name2; member_type3 member_name3; . . }
object_names;All the elements of the union declaration occupy the same physical space in
memory. Its size is the one of the greatest element of the declaration. all of them are
referring to the same location in memory, the modification of one of the elements will affect
the value of all of them. We cannot store different values in them independent of each
other.One of the uses a union may have is to unite an elementary type with an array or
structures of smaller elements. The exact alignment and order of the members of a union in
memory is platform dependant. Therefore be aware of possible portability issues with this
type of use.

3.Class
Class in C++ is same as structure.Class is a concept of OOP. In a class declaration, we
must use the keyword Class.The class variables are known as objects.A class ends with a
semi colon. The main difference of class and structure is, we can include functions in a
class.

23
4.Enumerated Data Type:
Enumerated data type provides a way for attaching names to numbers. It can be used to assign
names to integer constants.

enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2,


and so on.
enum shape {circle, square, triangle};
enum colour {red, blue, green, yellow};
enum position {off, on};
enum colour {red, blue, green, yellow};
In C++ the tag names can be used to declare new variables.
colour background;
In C++ each enumerated data type retains its own separate type.
C++ does not permit an int value to be automatically converted to an enum value.
colour background = blue; // allowed
colour background = 3; // error in C++
colour background = (colour) 3; // OK
int c = red; // valid
By default, the enumerators are assigned integer values starting with 0.
We can override the default value by explicitly assigning integer values to the enumerators.
enum colour { red, blue=4, green =8};
enum colour {red=5, blue, green};
C++ also permits the creation of anonymous enum (i.e., enum with out tag name).
enum {off, on}; here off à 0 and on à 1
int switch_1 = off;
int switch_2 = on;

New operators in C++ :


<< Insertion Operator
>> Extraction Operator
:: Scope Resolution Operator
: : * Pointer-to-member declaration
->* Pointer-to-member Operator
.* Pointer-to-member Operator
delete Memory Release Operator
endl Line Feed Operator
new Memory Allocation Operator
setw Field Width Operator

Scope Resolution Operator


C++ is a block structured language. The scope of a variable extends from the point of its
declaration till the end of the block containing the declaration. A variable declared inside
a block is said to be local to that block.
In C, the global version of a variable cannot be accessed from within the inner block.

24
C++ resolved this problem with the use of the scope resolution operator ( :: ).The scope
resolution operator ( :: ) can be used to uncover a hidden variable.
Syntax is :- : : variable-name
This operator allows access to the global version of a variable.

Manipulators
Manipulators are operators that are used to format the data display.
Commonly used manipulators are:
endl // causes a line feed when used in an output statement
setw // to specify field width and force the data to be printed right-justified

Symbolic Constants
Two ways of creating symbolic constant in C++.
1. Using the qualifier const
2. Defining a set of integer constants using enum keyword.
Any value declared as const cannot be modified by the program in any way. In C++, we
can use const in a constant expression.
const int size = 10;
char name[size]; // This is illegal in C.
const allows us to create typed constants.
#define - to create constants that have no type information.
The named constants are just like variables except that their values cannot be changed.
C++ requires a const to be initialized.
A const in C++ defaults, it is local to the file where it is declared. To make it global the
qualifier extern is used.
extern const int total = 100;
enum { X, Y, Z };
This is equivalent to
const int X = 0;const int Y = 1;const int Z = 2;

Reference Variables
A reference variable provides an alias for a previously defined variable.For eg., if we
make the variable sum a reference to the variable total, then sum and total can be used
interchangeably to represent that variable.
data-type & reference-name = variable-name
float total = 100;
float &sum = total;
A reference variable must be initialized at the time of declaration. This establishes
the correspondence between the reference and the data object which it names.
int x ;
int *p = &x ;

25
int & m = *p ;
void f ( int & x )
{
x = x + 10;
}
int main ( )
{
int m = 10;
f (m);
}

Special Assignment Expressions


Chained Assignment
x = (y = 10); // first 10 is assigned to y
or
x = y = 10; // and then to x
A chained statement cannot be used to initialize variables at the time of declaration.
float a = b = 12.34 // wrong
float a = 12.34, b = 12.34 // correct
Embedded Assignment
x = (y = 50) + 10;
Here the value 50 is assigned to y and then the result 50 + 10 = 60 is assigned to x.
This statement is identical to
y = 50;
x = y + 10;
Compound Assignment
A combination of the assignment operator with a binary operator.
x + = 10; += is known as compound operator
variable_1 op= variable_2
where op is a binary arithmetic operator

Control Structures
1. Sequence Structure (straight line)
2. Selection Structure (branching)
3. Loop Structure (iteration or repetition)
1.Sequence Structure (straight line)
1.1 if Statement-An if statement consists of a boolean expression followed by one or
more statements
The general form is
if (expression)
statement;

26
First expression is evaluated. If the outcome is nonzero then statement is executed.
otherwise, nothing happens.

2. Selection Structure (branching)


2.1 if-else Statement- An if statement can be followed by an optional else statement,
which executes when the boolean expression is false.
The general form is
if (expression)
statement1;
else
statement2;
First expression is evaluated. If the outcome is nonzero then statement1 is executed.
Otherwise, statement2 is executed.

2.2 The switch Statement


The switch statement provides a way of choosing between a set of alternatives, based
on the value of an expression. A switch statement allows a variable to be tested for
equality against a list of values.
The general form of the switch statement is:
switch (expression)
{
case constant1:
statements;
...
case constantn:
statements;
default:
statements;
}
First expression (called the switch tag) is evaluated, and the outcome is compared to
each of the numeric constants (called case labels), in the order they appear, until a
match is found. The statements following the matching case are then executed. Note
the plural: each case may be followed by zero or more statements (not just one
statement).
Execution continues until either a break statement is encountered or all intervening
statements until the end of the switch statement are executed.
The final default case is optional and is exercised if none of the earlier cases provide a
match.
switch (operator) {
case '+': result = operand1 + operand2;
break;

27
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
Note:-
nested if statements- can use one if or else if statement inside another if or else if
statement(s)
nested switch statements- can use one swicth statement inside another switch
statement(s).

3. Loop Structure (iteration or repetition)


3.1 The while Statement
WHILE LOOP-provides a way of repeating an statement while a condition holds.
The general form of the while statement is:
while (expression)
statement;
 First expression (called the loop condition) is evaluated. If the outcome is
nonzero then statement (called the loop body) is executed and the whole
process is repeated. Otherwise, the loop is terminated.
3.2 The do Statement
The do statement (also called do loop) is similar to the while statement, except that its
body is executed first and then the loop condition is examined.
The general form of the do statement is:
do
statement;
while (expression);
 First statement is executed and then expression is evaluated. If the outcome of
the latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
It is useful for situations where we need the loop body to be executed at least once,
regardless of the loop condition.The do loop is less frequently used than the while loop.

3.3 The for Statement


The for statement (also called for loop) is similar to the while statement, but has two
additional components: an expression which is evaluated only once before everything
else, and an expression which is evaluated once at the end of each iteration.

28
The general form of the for statement is:
for (expression1; expression2; expression3)
statement;
 First expression1 is evaluated. Each time round the loop, expression2 is
evaluated. If the outcome is nonzero then statement is executed and
expression3 is evaluated. Otherwise, the loop is terminated

Other Statements
The continue Statement- The continue statement terminates the current iteration of a
loop and instead jumps to the next iteration.
The break Statement- A break statement may appear inside a loop (while, do, or for) or
a switch statement. It causes a jump out of these constructs, and hence terminates them
The goto Statement- The goto statement provides the lowest-level of jumping. It has the
general form:
goto label;
 where label is an identifier which marks the jump destination of goto. The label
should be followed by a colon and appear before a statement within the same
function as the goto statement itself.
The return Statement- The return statement enables a function to return a value to its
caller.
It has the general form:
return expression;
where expression denotes the value returned by the function. The type of this value
should match the return type of the function. For a function whose return type is
void, expression should be empty:
return;
The return type of main is always int. The return value of main is what the program
returns to the operating system when it completes its execution.

Functions
A function provides a convenient way of packaging a computational recipe, so that it can
be used as often as required. A function definition consists of two parts: interface and
body.
1. The interface of a function (also called its prototype) specifies how it may be
used. It consists of three entities:
o The function name. This is simply a unique identifier.
o The function parameters (also called its signature). This is a set of zero or
more typed identifiers used for passing values to and from the function.
o The function return type. This specifies the type of value the function
returns.
A function which returns nothing should have the return type void.

29
2. The body of a function contains the computational steps (statements) that
comprise the function.
Using a function involves ‘calling’ it. A function call consists of the function name
followed by the call operator brackets ‘()’, inside which zero or more comma-separated
arguments appear. The number of arguments should match the number of function
parameters.Each argument is an expression whose type should match the type of the
corresponding parameter in the function interface.
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
Functions-benefits
 Dividing a program into functions.
o a major principle of top-down, structured programming.
 To reduce the size of the program.
 Code re-use.

Function Prototyping
 The prototype describes the function interface to the compiler by giving details such
as:
o The number and type of arguments
o The type of return values.
 It is a template
 When the function is called, the compiler uses the template to ensure that proper
arguments are passed, and the return value is treated correctly.
 Function prototype is a declaration statement in the calling program.

Type function-name ( argument-list ) ;

The argument-list contains the types and names of arguments that must be passed to
the function.Each argument variable must be declared independently inside the
parentheses.
float avg ( int x, int y) ; // correct
float avg ( int x, y) ; // illegal
In a function declaration, the names of the arguments are dummy variables and
therefore they are optional.
float avg ( int , int ) ;
The variable names in the prototype just act as placeholders and, therefore, if names are
used, they do not have to match the names used in the function call or function
definition.

30
void display( ); // function with an
void display(void); // empty argument list.

Inline function

One of the major objectives of using functions in a program is to save memory space, which becomes
appreciable when a function is likely to be called many times. However, every time a function is called, it takes
a lot of extra time in executing tasks such as jumping to the calling function. When a function is small, a
substantial percentage of execution time may be spent in such overheads and sometimes maybe the time
taken for jumping to the calling function will be greater than the time taken to execute that function.

One solution to this problem is to use macro definitions, commonly known as macros. Preprocessor macros
are popular in C, but the major drawback with macros is that they are not really functions and therefore, the
usual error checking process does not occur during compilation.

C++ has a different solution to this problem. To eliminate the time of calls to small functions, C++ proposes a
new function called inline function. An inline function is a function that is expanded in line when it is invoked
thus saving time. The compiler replaces the function call with the corresponding function code that reduces
the overhead of function calls.

We should note that inlining is only a request to the compiler, not a command. The compiler can ignore and
skip the request for inlining. The compiler may not perform inlining in the following circumstances:

 If a function contains a loop. (for, while, do-while)


 If a function is recursive.
 If a function contains static variables.
 If a function contains a switch command or goto statement.
 For a function not returning values, if a return statement exists. 

Syntax:

For an inline function, declaration and definition must be done together.

1 inline function-header
2 {
3 function-body
4 }

Example:

1 inline int cube(int s)


2 {
3 return s*s*s;
4 }
5 inline int inc(int a)
6 {

31
7
return ++a;
8
}
9
10
int main()
11
{
12
int a = 11;
13
cout << "The cube of 3 is: " << cube(3) << "n";
14
cout << "Incrementing a " << inc(a) << "n";
15
return 0;
16
}
17
Output:

When to use Inline function?

We can use Inline function as per our needs. Some useful recommendation are mentioned below-

 We can use the inline function when performance is needed.


 We can use the inline function over macros.
 We prefer to use the inline keyword outside the class with the function definition to hide
implementation details of the function.

Points to be remembered while using Inline functions

 We must keep inline functions small, small inline functions have better efficiency and good results.
 Inline functions do increase efficiency, but we should not turn all the functions inline. Because if we
make large functions inline, it may lead to code bloat and might end up decreasing the efficiency.
 It is recommended to define large functions outside the definition of a  class using scope resolution::
operator, because if we define such functions inside a class definition, then they might become inline
automatically and again affecting the efficiency of our code.

Advantages of Inline function

 Function call overhead doesn’t occur.


 It saves the overhead of a return call from a function.
 It saves the overhead of push/pop variables on the stack when the function is called.
 When we use the inline function it may enable the compiler to perform context-specific optimization
on the function body, such optimizations are not possible for normal function calls.
 It increases the locality of reference by utilizing the instruction cache.
 An inline function may be useful for embedded systems because inline can yield less code than the
function call preamble and return.

Limitations of Inline functions

 Large Inline functions cause Cache misses and affect efficiency negatively.


 Compilation overhead of copying the function body everywhere in the code at the time of compilation
which is negligible in the case of small programs, but it may make a big difference in large codebases.

32
 If we require address of the function in a program, the compiler cannot perform inlining on such
functions. Because for providing the address to a function, the compiler will have to allocate
storage to it. But inline functions don’t get storage, they are kept in Symbol table.
 Inline functions might cause thrashing because it might increase the size of the binary executable file.
Thrashing in memory causes the performance of the computer to degrade and it also affects the
efficiency of our code.
  The inline function may increase compile time overhead if someone tried to changes the code inside
the inline function then all the calling location has to be recompiled again because the compiler would
require to replace all the code once again to reflect the changes, otherwise it will continue with old
functionality without any change.

Function Overloading

Function Overloading in C++ can be defined as the process of having two or more member functions of a class
with the same name, but different in parameters. In function overloading, the function can be redefined either
by using different types of arguments or a different number of arguments according to the requirement. It is
only through these differences compiler can differentiate between the two overloaded functions.

One of the major advantages of Function overloading is that it increases the readability of the program
because we don’t need to use different names for the same action again and again.

By changing the Number of Arguments

In this way of function overloading, we define two functions with the same names but a different number of
parameters of the same type. For example, in the below-mentioned program, we have made two add()
functions to return the sum of two and three integers.

1 // first function definition


2 int add(int a, int b)
3 {
4     cout << a+b;
5 }
6
7 // second overloaded function definition
8 int add(int a, int b, int c)
9 {
10     cout << a+b+c;
11 }
Here add() function is said to be overloaded, as it has two definitions, one which accepts two arguments and
another which accepts three arguments. Which add() function will be called, depends on the number of
arguments.

1 int main()
2 {
3     add(10, 20);  // add() with 2 parameter will be called
4
5     add(10, 20, 30);  //sum() with 3 parameter will be called
6
7 }
1 #include <iostream>
2
3 using namespace std;
4

33
5 int add(int a, int b)
6 {
7     cout << a+b <<endl;
8     return 0;
9 }
10
11 int add(int a, int b, int c)
12 {
13     cout << a+b+c <<endl;
14     return 0;
15 }
16
17 int main()
18 {
19
20     add(20, 40);
21
22     add(40, 20, 30);
23 }

In the above example, we overload add() function by changing its number of arguments. First, we define an
add() function with two parameters, then we overload it by again defining the add() function but this time with
three parameters.

By having different types of Arguments

In this method, we define two or more functions with the same name and the same number of parameters,
but the data type used for these parameters are different. For example in this program, we have three add()
function, the first one gets two integer arguments, the second one gets two float arguments and the third one
gets two double arguments.

1 #include <iostream>
2
3 using namespace std;
4 int add(int x, int y) // first definition
5 {
6     cout<< x+y << endl;
7
8     return 0;
9 }
10
11 float add(float a, float b)
12 {
13     cout << a+b << endl;
14     return 0;
15 }
16
17
18

34
double add(double x, double y)
19 {
20     cout << x+y << endl;
21     return 0;
22 }
23
24 int main()
25 {
26
27
    add(20, 40);
28
29
    add(23.45f, 34.5f);
30
31
32     add(40.24, 20.433);
33
}

In the above example, we define add() function three times. First using integers as parameters, second using
float as parameters and third using double as a parameter.
Thus we override the add() function twice.

Advantages of function Overloading in C++

 We use function overloading to save the memory space, consistency, and readability of our program.
 With the use function overloading concept, we can develop more than one function with the same
name
 Function overloading shows the behavior of polymorphism that allows us to get different behavior,
although there will be some link using the same name of the function.
 Function overloading speeds up the execution of the program.
 Function overloading is used for code reusability and also to save memory.
 It helps application to load the class method based on the type of parameter.
 Code maintenance is easy.

Disadvantages of function Overloading in C++

 Function declarations that differ only by its return type cannot be overloaded with function
overloading process.
 Member function declarations with the same parameters or the same name types cannot be
overloaded if any one of them is declared as a static member function.

35
1 class XYZ{
2   static void func();
3   void func(); // error
4   };
 

Function Overloading and Ambiguity

When the compiler is unable to decide which function it should invoke first among the overloaded functions,
this situation is known as function overloading ambiguity. The compiler does not run the program if it shows
ambiguity error. Causes of Function Overloading ambiguity:

 Type Conversion.
 Function with default arguments.
 Function with a pass by reference

Default argument

A default argument is a value provided in a function declaration that is automatically assigned by the
compiler if the caller of the function doesn’t provide a value for the argument with a default value.

int sum(int x, int y, int z=0, int w=0)


{
    return (x + y + z + w);
}

/* Driver program to test above function*/


int main()
{
    cout << sum(10, 15) << endl;
    cout << sum(10, 15, 25) << endl;
    cout << sum(10, 15, 25, 30) << endl;
    return 0;
}

Output:
25
50
80

When Function overloading is done along with default values. Then we need to make sure it will not be
ambiguous.

Key Points:

 Default arguments are different from constant arguments as constant arguments can't be changed
whereas default arguments can be overwritten if required.
 Default arguments are overwritten when calling function provides values for them. For example, calling
of function sum(10, 15, 25, 30) overwrites the value of z and w to 25 and 30 respectively.

36
 During calling of function, arguments from calling function to called function are copied from left to
right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to x, y, and z. Therefore, the default value is
used for w only.
 Once default value is used for an argument in function definition, all subsequent arguments to it must
have default value. It can also be stated as default arguments are assigned from right to left. For
example, the following function definition is invalid as subsequent argument of default variable z is not
default.

37

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy