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

Unit 1 Notes

The document discusses the principles of Object-Oriented Programming (OOP) and contrasts it with Procedural Programming, highlighting key differences such as security, approach, and data handling. It outlines the advantages and disadvantages of OOP, including its modularity and complexity, and provides an overview of the structure of C++ programs, including data types, symbolic constants, and operators. The document serves as an introductory guide for understanding OOP concepts and the C++ programming language.

Uploaded by

yoxop87048
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)
5 views

Unit 1 Notes

The document discusses the principles of Object-Oriented Programming (OOP) and contrasts it with Procedural Programming, highlighting key differences such as security, approach, and data handling. It outlines the advantages and disadvantages of OOP, including its modularity and complexity, and provides an overview of the structure of C++ programs, including data types, symbolic constants, and operators. The document serves as an introductory guide for understanding OOP concepts and the C++ programming language.

Uploaded by

yoxop87048
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/ 34

School of Management Sciences, Varanasi

BCA-303: Object –Oriented Programming Using C++

Unit 1: Principles of Object-Oriented Programming and Introduction to C++

-------------------------------------------------------------------------------------------------------------------------------

Basic Concepts of Procedure-oriented and Object-oriented programming:

Object-oriented programming and procedural programming both are used to develop the applications.
Both of them are high-level programming languages.

Procedural Programming

It is defined as a programming language derived from the structure programming and based on calling
procedures. The procedures are the functions, routines, or subroutines that consist of the computational
steps required to be carried. It follows a step-by-step approach in order to break down a task into a set of
variables and routines via a sequence of instructions. During the program's execution, a procedure can be
called at any point, either by other procedures or by itself. The examples of procedural programming are
ALGOL, COBOL, BASIC, PASCAL, FORTRAN, and C.

As compared to object-oriented programming, procedural programming is less secure. Procedural


programming follows a top-down approach during the designing of a program. It gives importance to the
concept of the function and divides the large programs into smaller parts or called as functions.
Procedural programming is straightforward. Unlike object-oriented programming, there are no access
modifiers introduced in procedural programming.

Object-oriented programming

Object-oriented programming is a computer programming design philosophy or methodology that


organizes/ models software design around data or objects rather than functions and logic. It includes two
words, "object" and "oriented". In a dictionary object is an article or entity that exists in the real world.
The meaning of oriented is interested in a particular kind of thing or entity. The programming paradigm
where everything is represented as an object is known as a truly object-oriented programming
language. Smalltalk is said to be the first truly object-oriented programming language.

OOP is said to be the most popular programming model among developers. It is well suited for programs
that are large, complex, and actively updated or maintained. It makes the development and maintenance
of software easy by providing major concepts such as abstraction, inheritance, polymorphism, and
encapsulation. These four are also the four pillars of an object-oriented programming system.

1
OOPs, provide the ability to simulate real-world events much more effectively. We can provide the
solution to real-world problems if we are using the Object-Oriented Programming language. OOPs,
provide data hiding, whereas, in Procedure-oriented programming language, global data can be accessed
from anywhere.

The examples of OOPs are - C#, Python, C++, Java, PHP, Scala, Perl, etc.

Difference between Procedure Oriented and Object Oriented Programming:

S.no. Procedural Programming Object-oriented programming

1. It is a programming language that is derived Object-oriented programming is a computer


from structure programming and based upon programming design philosophy or methodology
the concept of calling procedures. It follows a that organizes/ models software design around
step-by-step approach in order to break down data or objects rather than functions and logic.
a task into a set of variables and routines via a
sequence of instructions.

2. It is less secure than OOPs. Data hiding is possible in object-oriented


programming due to abstraction. So, it is more
secure than procedural programming.

3. It follows a top-down approach. It follows a bottom-up approach.

4. In procedural programming, data moves In OOP, objects can move and communicate
freely within the system from one function to with each other via member functions.
another.

5. It is structure/procedure-oriented. It is object-oriented.

6. There are no access modifiers in procedural The access modifiers in OOP are named as
programming. private, public, and protected.

2
7. Procedural programming does not have the There is a feature of inheritance in object-
concept of inheritance. oriented programming.

8. There is no code reusability present in It offers code reusability by using the feature of
procedural programming. inheritance.

9. Overloading is not possible in procedural In OOP, there is a concept of function


programming. overloading and operator overloading.

10. It gives importance to functions over data. It gives importance to data over functions.

11. In procedural programming, there are no In OOP, there is an appearance of virtual classes
virtual classes. in inheritance.

12. It is not appropriate for complex problems. It is appropriate for complex problems.

13. There is not any proper way for data hiding. There is a possibility of data hiding.

14. In Procedural programming, a program is In OOP, a program is divided into small parts
divided into small programs that are referred that are referred to as objects.
to as functions.

15. Examples of Procedural programming The examples of object-oriented programming


include C, Fortran, Pascal, and VB. are- .NET, C#, Python, Java, VB.NET, and C++.

Advantages and disadvantages of OOP:

Advantages:

 We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development
time and higher productivity,

3
 OOP language allows breaking the program into the bit-sized problems that can be solved easily
(one object at a time).

 The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.

 OOP systems can be easily upgraded from small to large systems.

 It is possible that multiple instances of objects co-exist without any interference,

 It is very easy to partition the work in a project based on objects.

 It is possible to map the objects in problem domain to those in the program.

 The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.

 By using inheritance, we can eliminate redundant code and extend the use of existing classes.

 Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.

 The data-centered design approach enables us to capture more details of model in an


implementable form.

Disadvantages of OOP

 The length of the programs developed using OOP language is much larger than the procedural
approach. Since the program becomes larger in size, it requires more time to be executed that
leads to slower execution of the program.
 We cannot apply OOP everywhere as it is not a universal language. It is applied only when it is
required. It is not suitable for all types of problems.
 Programmers need to have brilliant designing skill and programming skill along with proper
planning because using OOP is little bit tricky.
 OOPs take time to get used to it. The thought process involved in object-oriented programming
may not be natural for some people.
 Everything is treated as object in OOP so before applying it we need to have excellent thinking in
terms of objects.

4
Structure of C++ program:

Programs are a sequence of instructions or statements. These statements form the structure of a C++
program. C++ program structure is divided into various sections, namely, headers, class definition,
member functions definitions and main function.

Note that C++ provides the flexibility of writing a program with or without a class and its member
functions definitions. A simple C++ program (without a class) includes comments, headers, namespace,
main() and input/output statements.

Comments are a vital element of a program that is used to increase the readability of a program and to
describe its functioning. Comments are not executable statements and hence, do not increase the size of a
file.

C++ supports two comment styles: single line comment and multiline comment. Single line comments are
used to define line-by-line descriptions. Double slash (//) is used to represent single line comments. To
understand the concept of single line comment, consider this statement.

5
/ / An example to demonstrate single line comment It can also be written as

/ / An example to demonstrate

/ / single line comment

Multiline comments are used to define multiple lines descriptions and are represented as / * * /. For
example, consider this statement.

/* An example to demonstrate multiline comment */

Generally, multiline comments are not used in C++ as they require more space on the line. However, they
are useful within the program statements where single line comments cannot be used. For example,
consider this statement.

for(int i = 0; i<10; //loop runs 10 times i++)

Compiler ignores everything written after the single line comment and hence, an error occurs. Therefore,
in this case multiline comments are used. For example, consider this statement.

for(int i = 0; i<10; /*loop runs 10 times */ i++)

Headers: Generally, a program includes various programming elements like built-in functions, classes,
keywords, constants, operators, etc., that are already defined in the standard C++ library. In order to use
such pre-defined elements in a program, an appropriate header must be included in the program. The
standard headers contain the information like prototype, definition and return type of library
functions, data type of constants, etc. As a result, programmers do not need to explicitly declare (or
define) the predefined programming elements.

Standard headers are specified in a program through the preprocessor directive” #include. In Figure, the
iostream header is used. When the compiler processes the instruction #inc1ude<iostream>, it includes the
contents of iostream in the program. This enables the programmer to use standard input,
output and error facilities that are provided only through the standard streams defined in <iostream>.
These standard streams process data as a stream of characters, that is, data is read and displayed in a
continuous flow. The standard streams defined in <iostream> are listed here.

• cin (pronounced “see in”) : It is the standard input stream that is associated with the standard input
device (keyboard) and is used to take the input from users.

• cout (pronounced “see out”) : It is the standard output stream that is associated with the standard output
device (monitor) and is used to display the output to users.
6
Namespace: Since its creation, C++ has gone through many changes by the C++ Standards Committee.
One of the new features added to this language is namespace. A namespace permits grouping of various
entities like classes, objects, functions and various C++ tokens, etc., under a single name. Different users
can create separate namespaces and thus can use similar names of the entities. This avoids compile-time

Main Function: The main () is a startup function that starts the execution of a C++ program. All C++
statements that need to be executed are written within main ( ). The compiler executes all the instructions
written within the opening and closing curly braces’ {}’ that enclose the body of main ( ). Once all the
instructions in main () are executed, the control passes out of main ( ), terminating the entire program and
returning a value to the operating system.

C++ Data Types:

In C++, data types are declarations for variables. This determines the type and size of data
associated with variables. The table below shows the fundamental data types, their meaning, and
their sizes (in bytes):

Data Type Meaning Size (in Bytes)

int Integer 2 or 4

float Floating-point 4

double Double Floating-point 8

char Character 1

wchar_t Wide Character 2

bool Boolean 1

void Empty 0

1. C++ int

 The int keyword is used to indicate integers.

 Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.

7
 For example, int salary = 85000;

2. C++ float and double

 float and double are used to store floating-point numbers (decimals and exponentials).

 The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the
precision of float. To learn more, visit C++ float and double.

 For example, float area = 64.74; double volume = 134.64534;

 As mentioned above, these two data types are also used for exponentials.
 For example, double distance = 45E12 // 45E12 is equal to 45*10^12

3. C++ char

 Keyword char is used for characters.

 Its size is 1 byte.

 Characters in C++ are enclosed inside single quotes ' '.

 For example, char test = 'h';

Note: In C++, an integer value is stored in a char variable rather than the character itself.

4. C++ bool

 The bool data type has one of two possible values: true or false.

 Booleans are used in conditional statements and loops (which we will learn in later chapters).

 For example,bool cond = false;

5. C++ void

 The void keyword indicates an absence of data. It means "nothing" or "no value".

 We will use void when we learn about functions and pointers.

Note: We cannot declare variables of the void type.

8
Symbolic constants and reference by variables:

A symbolic constant is a name given to some numeric constant, or a character constant or string constant,
or any other constants. Symbolic constant names are also known as constant identifiers. Pre-processor
directive #define is used for defining symbolic constants.

Syntax for Creating Symbolic Constants

#define symbolic_constant_name value_of_the_constant

Symbolic Constants Examples

#define PI 3.141592

#define MAX 500

Here PI, SIZE are symbolic constants.

Note: symbolic constants names are written in uppercase by convention, but it is not required.

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 provide the following types of operators −

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Misc Operators

9
1) Arithmetic Operators

There are following arithmetic operators supported by C++ language −

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

Operator Description Example

+ Adds two operands A + B will give 30

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

* Multiplies both operands A * B will give 200

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

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value A++ will give 11


by one

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


by one

2) Relational Operators

There are following relational operators supported by C++ language

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

Operator Description Example

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

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


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

> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.

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


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

>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if
yes then condition becomes true.

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


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

3) Logical Operators

There are following logical operators supported by C++ language.

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

Operator Description Example

11
&& Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.

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


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

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


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

4) Bitwise Operators

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

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

12
-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then −

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 exists in (A | B) will give 61 which is 0011 1101
either operand.

^ Binary XOR Operator copies the bit if it is


(A ^ B) will give 49 which is 0011 0001
set in one operand but not both.

~ Binary Ones Complement Operator is unary (~A ) will give -61 which is 1100 0011 in 2's
and has the effect of 'flipping' bits. complement form due to a signed binary
number.

<< Binary Left Shift Operator. The left operands


value is moved left by the number of bits A << 2 will give 240 which is 1111 0000
specified by the right operand.

>> Binary Right Shift Operator. The left


operands value is moved right by the number A >> 2 will give 15 which is 0000 1111
of bits specified by the right operand.

13
5) Assignment Operators

There are following assignment operators supported by C++ language −

Operator Description Example

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


from right side operands to left side operand. C

+= Add AND assignment operator, It adds right


operand to the left operand and assign the result C += A is equivalent to C = C + A
to left operand.

-= Subtract AND assignment operator, It subtracts


right operand from the left operand and assign C -= A is equivalent to C = C - A
the result to left operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left operand.

/= Divide AND assignment operator, It divides left


operand with the right operand and assign the C /= A is equivalent to C = C / A
result to left operand.

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

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

14
>>= 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 operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

6) Other Operators

The following table lists some other operators that C++ supports.

Sr.No Operator & Description

1 sizeof

sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and
will return 4.

2 Condition ? X : Y

Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of
Y.

3 ,

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.

4 . (dot) and -> (arrow)

Member operators are used to reference individual members of classes, structures, and unions.

15
5 Cast

Casting operators convert one data type to another. For example, int(2.2000) would return 2.

6 &

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

7 *

Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

Operators Precedence in C++

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

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

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

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

Multiplicative */% Left to right

Additive +- Left to right

16
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

Control Structures

Control Structures are just a way to specify flow of control in programs. Any algorithm or program can
be clearer and understood if they use self-contained modules called as logic or control structures. It
basically analyzes and chooses in which direction a program flows based on certain parameters or
conditions. There are three basic types of logic, or flow of control, known as:

1. Sequence logic, or sequential flow

2. Selection logic, or conditional flow

17
3. Iteration logic, or repetitive flow

Let us see them in detail:

1. Sequential Logic (Sequential Flow)

Sequential logic as the name suggests follows a serial or sequential flow in which the flow depends on the
series of instructions given to the computer. Unless new instructions are given, the modules are executed
in the obvious sequence. The sequences may be given, by means of numbered steps explicitly. Also,
implicitly follows the order in which modules are written. Most of the processing, even some complex
problems, will generally follow this elementary flow pattern.

2. Selection Logic (Conditional Flow)

Selection Logic simply involves a number of conditions or parameters which decides one out of several
written modules. The structures which use these type of logic are known as Conditional Structures.
These structures can be of three types:

 Single Alternative

If (condition) then:

[Module A]

[End of If structure]

18
 Double Alternative

If (Condition), then:

[Module A]

Else:

[Module B]

[End if structure]

 Multiple Alternatives

If (condition A), then:

[Module A]

Else if (condition B), then:

[Module B]

..

..

Else if (condition N), then:

[Module N]

[End If structure]

In this way, the flow of the program depends on the set of conditions that are written. This can be more
understood by the following flow charts:

3. Iteration Logic (Repetitive Flow)


The Iteration logic employs a loop which involves a repeat statement followed by a module
known as the body of a loop.
The two types of these structures are:

 Repeat-For Structure

Repeat for i = A to N by I:
19
[Module]

[End of loop]

Here, A is the initial value, N is the end value and I is the increment. The loop ends when A>B. K
increases or decreases according to the positive and negative value of I respectively.

 Repeat-While Structure
It also uses a condition to control the loop. This structure has the form:

Repeat while condition:

[Module]

[End of Loop]

C++ Functions

The function in C++ language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity
and code reusability.

Advantage of functions in C

There are many advantages of functions.

1) Code Reusability: By creating functions in C++, you can call it many times. So we don't need to write
the same code again and again.

2) Code optimization: It makes the code optimized, we don't need to write much code. But if you use
functions, you need to write the logic only once and you can reuse it several times.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x),
cos(x), exp(x), etc.

20
2. User-defined functions: are the functions which are created by the C++ programmer, so that he/she
can use it many times. It reduces complexity of a big program and optimizes the code.

Declaration of a function

The syntax of creating function in C++ language is given below:

return_type function_name(data type parameter...)

//code to be executed

C++ Function Example

1. #include <iostream>

2. using namespace std;

3. void func() {

4. static int i=0; //static variable

5. int j=0; //local variable

6. i++;

7. j++;

8. cout<<"i=" << i<<" and j=" <<j<<endl;


21
9. }

10. int main()

11. {

12. func();

13. func();

14. func();

15. }

Output:

i= 1 and j= 1

i= 2 and j= 1

i= 3 and j= 1

C++ Function Prototype

A function prototype is a declaration of the function that tells the program about the type of the value
returned by the function and the number and type of arguments. Function prototyping is one very useful
feature of C++ function. A function prototype describes the function interface to the compiler by giving
details such as the number and type of arguments and the type of return values.

The prototype declaration looks just like a function definition except that it has no body i.e., its code is
missing. This is the time you knew the difference between a declaration and a definition. A declaration
introduces a (function) name to the program whereas a definition is a declaration that also tells the
program what the function is doing and how it is doing.

Thus the above given examples are function definitions and the following are declarations or shall we say,
function prototypes:

int absval (int a);

int gcd (int n1, int n2);

Therefore, you can say that a function prototype has the following parts:
22
 return type

 name of the function

 argument list

Let's look at the following function prototype: int sum(int n1, int n2);

Here,

 return type - int

 name of the function - sum

 argument list - (int n1, int n2)

Since every function prototype is followed by a semicolon, so at last there will be ; as in the above
function prototype.

Tip - A function declaration can skip the argument names but a function definition, can not.

Use of Void

As you know about void data type that it specifies an empty set of values and it is used as the return type
for functions that do not return a value. Thus, a function that does not return a value is declared as
follows:

void function_name(parameter list);

By declaring a function's return type void, one makes sure that the function cannot be used in an
assignment statement.

Tip - If a function does not return a result, declare the result type as void.

A function that does not require any parameter (i.e., it has an empty argument list) can be declared as
follows:

return_type function_name(void);

Tip - If a function takes no argument, you should specify void in its prototype.

23
As already mentioned if you omit the type specifier of a function, it is assumed to be returning int values.
For the functions returning non-integer values, the type specifier must be given.

A function prototype can either appear before the definition of calling the function (such prototypes are
known as global prototypes) or within the definition of calling function (such prototypes are known as
local prototypes).

C++ Function Definition

The general form of a function definition is as given below:

return_type function_name(parameter list)

body of the function

Here, the return_type specifies the type of value that the return statement of the functions returns. It may
be any valid C++ data type. If no type is specified, the compiler assumes that the function returns an
integer value. The parameter list is a common-separated list of variables of a function referred to as its
arguments. A function may be without any parameters, in which case, the parameter list is empty. Here
are some examples of functions. Below is a function having only one parameter of int type and return
type also as int :

int absval(int a) // functions headers

return (a < 0 ? -a : a) ; //body of function absval

Here is another function definition example. This function has return type as int, and have two integer
parameters

int gcd(int n1, int n2)

// return the greatest common divisor

24
int temp;

while(n2)

temp = n2 ;

n2 = n1%n2 ;

n1 = temp ;

return n1 ;

C++ Function Prototype & Function Definition Example

Let's take an example program, demonstrating function prototype and function definition in C++. This
program also uses function calling, which is covered in C++ Calling Function tutorial coming in the next
chapter.

/* C++ Function Prototype and C++ Function Definition */

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

int add(int, int); // function prototype

int subtract(int, int); // function prototype

int multiply(int, int); // function prototype

int divide(int, int); // function prototype

void main()

25
clrscr();

int a, b;

cout<<"Enter any two number: ";

cin>>a>>b;

cout<<"\nSummation = "<<add(a, b);

cout<<"\nSubtraction = "<<subtract(a, b);

cout<<"\nMultiplication = "<<multiply(a, b);

cout<<"\nDivision = "<<divide(a, b);

getch();

int add(int x, int y) // function definition

int res;

res = x + y;

return res;

int subtract(int x, int y) // function definition

int res;

res = x - y;

return res;

int multiply(int x, int y) // function definition

26
{

int res;

res = x * y;

return res;

int divide(int x, int y) // function definition

if(y==0)

cout<<"\n\nDivide by Zero Error..!!";

cout<<"\nPress any key to exit...";

getch();

exit(1);

else

int res;

res = x / y;

return res;

C++ Return by Reference

27
Example: Return by Reference

#include <iostream>

using namespace std;

// global variable

int num;

// function declaration

int& test();

int main() {

// assign 5 to num variable

// equivalent to num = 5;

test() = 5;

cout << num;

return 0;

// function definition

// returns the address of num variable

int& test() {

return num;

The return statement is return num;. Unlike return by value, this statement doesn't return value of num,
instead it returns the variable itself (address).

So, when the variable is returned, it can be assigned a value as done in test() = 5;

This stores 5 to the variable num, which is displayed onto the screen.
28
Important Things to Remember When Returning by Reference.

 Ordinary function returns value but this function doesn't. Hence, you cannot return a constant
from the function.

int& test()

{ return 2; }

 You cannot return a local variable from this function.

int& test()

{ int n = 2; return n; }

Inline Functions:

C++ inline function is powerful concept that is commonly used with classes. 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.

Any change to an inline function could require all clients of the function to be recompiled because
compiler would need to replace all the code once again otherwise it will continue with old
functionality.

To inline a function, place the keyword inline before the function name and define the function before
any calls are made to the function. The compiler can ignore the inline qualifier in case defined
function is more than a line.

A function definition in a class definition is an inline function definition, even without the use of the
inline specifier.

Following is an example, which makes use of inline function to return max of two numbers −

#include <iostream>

using namespace std;

29
inline int Max(int x, int y) {

return (x > y)? x : y;

// Main function for the program

int main() {

cout << "Max (20,10): " << Max(20,10) << endl;

cout << "Max (0,200): " << Max(0,200) << endl;

cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;

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

Max (20,10): 20

Max (0,200): 200

Max (100,1010): 1010

Default Arguments

A default argument is a value in the function declaration automatically assigned by the compiler
if the calling function does not pass any value to that argument.

Characteristics for defining the default arguments

Following are the rules of declaring default arguments -

o The values passed in the default arguments are not constant. These values can be
overwritten if the value is passed to the function. If not, the previously declared value
retains.

o During the calling of function, the values are copied from left to right.
30
o All the values that will be given default value will be on the right.

Example

o void function(int x, int y, int z = 0)


Explanation - The above function is valid. Here z is the value that is predefined as a part
of the default argument.

o Void function(int x, int z = 0, int y)


Explanation - The above function is invalid. Here z is the value defined in between, and it
is not accepted.

Code

1. #include<iostream>

2. using namespace std;

3. int sum(int x, int y, int z=0, int w=0) // Here there are two values in the default argumen
ts

4. { // Both z and w are initialised to zero

5. return (x + y + z + w); // return sum of all parameter values

6. }

7. int main()

8. {

9. cout << sum(10, 15) << endl; // x = 10, y = 15, z = 0, w = 0

10. cout << sum(10, 15, 25) << endl; // x = 10, y = 15, z = 25, w = 0

11. cout << sum(10, 15, 25, 30) << endl; // x = 10, y = 15, z = 25, w = 30

12. return 0;

13. }

Output
31
25

50

80

Explanation

In the above program, we have called the sum function three times.

o Sum(10,15)
When this function is called, it reaches the definition of the sum. There it initializes x to
10 y to 15, and the rest values are zero by default as no value is passed. And all the values
after sum give 25 as output.

o Sum(10, 15, 25)


When this function is called, x remains 10, y remains 15, the third parameter z that is
passed is initialized to 25 instead of zero. And the last value remains 0. The sum of x, y,
z, w, is 50 which is returned as output.

o Sum(10, 15, 25, 30)


In this function call, there are four parameter values passed into the function with x as 10,
y as 15, z is 25, and w as 30. All the values are then summed up to give 80 as the output.

Function Overloading

Function overloading is a C++ programming feature that allows us to have more than one function having
same name but different parameter list, when I say parameter list, it means the data type and sequence of
the parameters, for example the parameters list of a function myfuncn(int a, float b) is (int, float) which is
different from the function myfuncn(float a, int b) parameter list (float, int). Function overloading is
a compile-time polymorphism.
Now that we know what is parameter list lets see the rules of overloading: we can have following
functions in the same scope.

sum(int num1, int num2)

sum(int num1, int num2, int num3)

32
sum(int num1, double num2)

The easiest way to remember this rule is that the parameters should qualify any one or more of the
following conditions, they should have different type, number or sequence of parameters.

For example:
These two functions have different parameter type:

sum(int num1, int num2)

sum(double num1, double num2)

These two have different number of parameters:

sum(int num1, int num2)

sum(int num1, int num2, int num3)

These two have different sequence of parameters:

sum(int num1, double num2)

sum(double num1, int num2)

All of the above three cases are valid case of overloading. We can have any number of functions, just
remember that the parameter list should be different. For example:

int sum(int, int)

double sum(int, int)

This is not allowed as the parameter list is same. Even though they have different return types, its not
valid.

Function overloading Example

Let’s take an example to understand function overloading in C++.

#include <iostream>

using namespace std;

class Addition {

public:
33
int sum(int num1,int num2) {

return num1+num2;

int sum(int num1,int num2, int num3) {

return num1+num2+num3;

};

int main(void) {

Addition obj;

cout<<obj.sum(20, 15)<<endl;

cout<<obj.sum(81, 100, 10);

return 0;

Output:

35

191

Advantages of Function overloading

The main advantage of function overloading is to the improve the code readability and allows code
reusability. In the example 1, we have seen how we were able to have more than one function for the
same task (addition) with different parameters; this allowed us to add two integer numbers as well as
three integer numbers, if we wanted we could have some more functions with same name and four or five
arguments.
Imagine if we didn’t have function overloading, we either have the limitation to add only two integers or
we had to write different name functions for the same task addition, this would reduce the code
readability and reusability.

34

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