0% found this document useful (0 votes)
20 views24 pages

Unit 4 Oops

The document provides an overview of object-oriented programming concepts in C++, including: 1. It discusses the basic structure of C++ programs and key concepts like namespaces, identifiers, variables, constants, and control structures. 2. It then covers C++ functions such as simple functions, call-by-reference, function overloading, default arguments, and friend functions. 3. The document also provides a comparison between C and C++, highlighting features like polymorphism and inheritance that are possible in C++ but not in C.

Uploaded by

Ananya Dudeja
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)
20 views24 pages

Unit 4 Oops

The document provides an overview of object-oriented programming concepts in C++, including: 1. It discusses the basic structure of C++ programs and key concepts like namespaces, identifiers, variables, constants, and control structures. 2. It then covers C++ functions such as simple functions, call-by-reference, function overloading, default arguments, and friend functions. 3. The document also provides a comparison between C and C++, highlighting features like polymorphism and inheritance that are possible in C++ but not in C.

Uploaded by

Ananya Dudeja
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/ 24

lOMoARcPSD|27431833

Unit-4 OOPs

Object Oriented Programming (Dr. A.P.J. Abdul Kalam Technical University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Ananya Dudeja ([email protected])
lOMoARcPSD|27431833

Unit-4

Syllabus

UNIT-4 : C++ BASICS & FUNCTIONS


C++ Basics : Overview, Program structure, namespace, identifiers, variables,
constants, enum, operators, typecasting, control structures.
C++ Functions : Simple functions, Call and Return by reference, Inline
functions, Macro Vs. Inline functions, Overloading of functions, default
arguments, friend functions, virtual functions.

Overview of C language:

1. C language is known as structure oriented language or procedure oriented


language

2. Employs top-down programming approach where a problem is viewed as a


sequence of tasks to be performed.

3. All program code of c can be executed in C++ but converse many not be
possible

4. Function overloading and operator overloading are not possible.

5. Local variables can be declared only at the beginning of the block.

6. Program controls are through jumps and calls to subroutines.

7. Polymorphism, encapsulation and inheritance are not possible.

For solving the problems, the problem is divided into a number of modules. Each
module is a subprogram.

8. Data abstraction property is not supported by procedure oriented language.

9. Data in procedure oriented language is open and can be accessed by any


function.

Overview of C++ language:

1. C++ can be considered as an incremental version of c language which consists


all programming language constructs with newly added features of object oriented
programming.

2. C++ is structure(procedure) oriented and object oriented programming language.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

3. The file extension of C++ program is “.CPP”

4. Function overloading and operator overloading are possible.

5. Variables can be declared in inline i.e when required

6. In c++ more emphasis is give on data rather than procedures

7. Polymorphism, encapsulation and inheritance are possible.

8. Data abstraction property is supported by c++.

9. Data access is limited. It can be accessed by providing various visibility modes


both for data and member functions by providing data security by data hiding

10. Dynamic binding is supported by C++

11. It supports all features of c language

12. It can be called as an incremental version of c language

BASIC STRUCTURE OF C++ LANGUAGE

The program written in C++ language follows this basic structure. The sequence of
sections should be as they are in the basic structure. A C program should have one
or more sections but the sequence of sections is to be followed.

1. Documentation section : comes first and is used to document the use of logic or
reasons in your program. The documentation is done in C language with /* and */

2. Linking section : This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section.
e.g. #include using namespace std

3. Definition section: It is used to declare some constants and assign them some
value. e.g. #define MAX 25 Here #define is a compiler directive which tells the
compiler whenever MAX is found in the program replace it with 25.

4. Global declaration section & class declarations: the variables and class
definitions which are used throughout the program (including main and other
functions) are declared so as to make them global

5.Member function definition : The data components of a class are called data
members and function components of a class are called member functions

6. Main function: It tells the compiler where to start the execution

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

from main() {point from execution starts}

Main function has two sections

1. declaration section : In this the variables and their data types are declared.

2. Executable section or instruction section : This has the part of program which
actually performs the task we need.
section main() {

Declaration section

Executable section}

namespace: namespace is used to define a scope that could hold global identifiers.

ex:-namespace scope for c++ standard library.

A classes ,functions and templates are declared within the namespace named

std using namespace std;-->directive can be used.

user defined name space:

syntax for defining name space is

namespace namespace_name {

//declarations of variables.functions,classes etc...}

ex:

#include<iostream>

using namespace std;

namespace sample {`int m;

void display(int n){

cout<<"in namespace N="<<n<<endl; }}

using namespace sample;

int main() {int a=5, m=100;

display(200);

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

cout<<"M in sample name space:"<<sample::m;

return 0;}

#include<iostream>

This directive causes the preprocessor to add content of iostream file to the
program.

some old versions of C++ used iostream.h .if complier does not support ANSI
(american nation standard institute) C++ then use header file iostream.h

IDENTIFIERS: Identifiers are the names given to various program elements such
as variables, functions and arrays. These are user defined names consisting of
sequence of letters and digits.

Rules for declaring identifiers:

฀ The first character must be an alphabet or underscore.

฀ It must consist of only letters, digits and underscore.

฀ Identifiers may have any length but only first 31 characters are significant.

฀ It must not contain white space or blank space.

฀ We should not use keywords as identifiers.

฀ Upper and lower case letters are different.

Example: ab Ab aB AB are treated differently

Examples of valid identifiers:

a, x, n, num, SUM, fact, grand_total, sum_of_digits, sum1

Examples of Invalid identifiers: $amount, ³num´, grand-total, sum of digits, 4num.

$amount : Special character is not permitted

grand-total : hyphen is not permitted.

Space of digits : blank spaces between the words are not allowed.

4num : should not start with a number (first character must be a letter or
underscore

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

Note: Some compilers of C recognize only the first 8 characters only; because of
this they are unable to distinguish identifiers with the words of length more than
eight characters.

Variables:A named memory location is called variable. OR

It is an identifier used to store the value of particular data type in the memory.

Rules for declaring Variables names:

฀ The first character must be an alphabet or underscore.

฀ It must consist of only letters, digits and underscore.

฀ Identifiers may have any length but only first 31 characters are significant.

฀ It must not contain white space or blank space.

฀ We should not use keywords as identifiers.

฀ Upper and lower case letters are different.

฀ Variable names must be unique in the given

scope Ex:int a,b,a;//is in valid

Int a,b;//is valid

Variable declaration: The declaration of variable gives the name for memory
location and its size and specifies the range of value that can be stored in that
location.

Syntax:

Data type variable name;

Ex: int a=10;

Data =10, Address 2000

float x=2.3;

x= 2.300000 address =5000

CONSTANTS:

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

Constants refer to values that do not change during the execution of a program.

Constants can be divided into two major categories:

1. Primary constants:

a)Numeric constants

฀ Integer constants.

฀ Floating-point (real) constants.

b)Character constants

฀ Single character constants

฀ String constants

2.Secondary constants:

฀ Enumeration constants.

฀ Symbolic constants.

฀ Arrays, unions, etc.

Rules for declaring constants:

1.Commas and blank spaces are not permitted within the constant.

2.The constant can be preceded by minus (-) signed if required.

3.The value of a constant must be within its minimum bounds of its specified data
type.

Integer constants: An integer constant is an integer-valued number. It consists of


sequence of digits. Integer constants can be written in three different number
systems:

1.Decimal integer (base 10): It consists of set of digits, 0 to 9.

2.Octal integer (base 8).: It consists of set of digits, 0 to 9.

3.Hexadecimal (base 16): It consists of set of digits, 0 to 9 and alphabets A, B, C,


D, E, and F.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

Floating point constants or Real constants : The numbers with fractional parts are
called real constants.

These are the numbers with base-10 which contains either a decimal part or
exponent (or both).

Decimal notation: 1234.56, 75.098, 0.0002, -0.00674 (valid notations)

Exponent or scientific notation:

General form: Mantissa e exponent

Mantissa: It is a real number expressed in decimal notation or an integer notation.

Exponent: It is an integer number with an optional plus (+) or minus (-) sign.

E or e: The letter separating the mantissa and decimal part.

Ex: (Valid notations)

1.23456E+3 (1.23456×10 )3

Character constants:-

Single character constants: It is character(or any symbol or digit) enclosed within


single quotes.

Ex: „a‟ „1‟ „*‟

Every Character constants have integer values known as ASCII values

String constants or string literal:

String constant is a sequence of zero or more characters enclosed by double quotes.

Example:

“MRCET” “12345”

Enumeration:

An enumerated type (also called enumeration or enum) is a data type consisting of


a set of named values called elements, members or enumerators of the type.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

The enumerator names are usually identifiers that behave as constants in the
language. A variable that has been declared as having an enumerated type can be
assigned any of the enumerators as a value.

The enumeration data type is defined as follows:

Syntax: enum identifier {value1,value2,……valuen};

Declaration of variables of this new type:

Ex: enum week{ sunday, monday, tuesday, wednesday, thursday, friday,


saturday};

declaration of variable:

enum week today;

today=wednesday;

#include <iotream.h>

enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};

int main(){

enum week today;

today=wednesday;

cout<< today+1<<" day";

return 0; }

Output 4 day

OPERATORS AND EXPRESSIONS

An operator is a symbol which represents a particular operation that can be


performed on data. An operand is the object on which an operation is performed.

By combining the operators and operands we form an expression. An expression is


a sequence of operands and operators that reduces to a single value.

C operators can be classified as

1. Arithmetic operators

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment or Decrement operators

6. Conditional operator

7. Bit wise operators

8. unary operator

9. Special operators

10.Additional operators in c++

Control statements:-The flow of execution of statements in a program is called as


control. Control statement is a statement which controls flow of execution of the
program. Control statements are classified into following categories.

1.Sequential control statements

2.Conditional control statements

3.Unconditional control statements

1.Sequential control statements:- Sequential control statements ensures that the


instructions(or statements) are executed in the same order in which they appear in
the program. i.e. By default system executes the statements in the program in
sequential order.

2.Conditional control statements :Statements that are executed when a condition


is true. These statements are divided into three categories. they are

1.Decision making statements

2.Switch case control statement or

3.Loop control statements or repetitions

1.Decision making statements:- These statements are used to control the flow of
execution of a program

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

by making a decision depending on a condition, hence they are named as decision


making statements.

Decision making statements are of four types

1.Simple if

2.if else

3.nested if else

4.If else ladder

Unconditional Control Statements

Unconditional control statements do not need to satisfy any condition. They


immediately move control from one part of the program to another part.
Unconditional statements in C++ include:

goto: A goto statement directs control to another part of the program.

break: A break statement terminates a loop (a repeated structure)

continue: A continue statement is used in loops to repeat the loop for the next value
by transferring control back to the beginning of the loop and ignoring the
statements that come after it.

FUNCTION OVERLOADING

Definition:-Overloading refers to the use of the same thing for different


purposes.Function overloading means we can use the same function name to create
functions that perform a variety of different tasks.

฀ Using the concept of function overloading, we can design a family of functions


with one function name but with different argument lists.

฀ The correct function to be invoked is determined by checking the number and


type of the arguments but not on the function type.

฀ The return type do not play any role in function overloading.

For example, an overloaded add() function handles different type of data as shown

below.

//declarations

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

int add(int a, int b); //prototype 1

int add(int a, int b, int c); //prototype 2

double add(double x, double y); //prototype 3

double add(int p,double q); //prototype 4

double add(double p, int q); //prototype 5

// function calls

cout<< add(5,10); // uses prototype 1

cout<< add(15,10.0); // uses prototype 2

cout<< add(12.5,7.5); // uses prototype 3

cout<< add(5,10,15); // uses prototype 4

cout<< add(.75,5); // uses prototype 5

Typecasting:

Type casting refers to the conversion of one data type to another in a program.
Typecasting can be done in two ways: automatically by the compiler and manually
by the programmer or user. Type Casting is also known as Type Conversion.

For example, suppose the given data is an integer type, and we want to convert it
into float type.

int num = 5;

float x;

x = float(num);

x = 5.0

Type Casting is divided into two types: Implicit conversion or Implicit Type
Casting and Explicit Type Conversion or Explicit Type Casting.

Implicit Type Casting or Implicit Type Conversion

It is known as the automatic type casting.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

It automatically converted from one data type to another without any external
intervention such as programmer or user. It means the compiler automatically
converts one data type to another.

All data type is automatically upgraded to the largest type without losing any
information.

It can only apply in a program if both variables are compatible with each other.

Explicit Type Casting or Explicit Type Conversion

It is also known as the manual type casting in a program.

It is manually cast by the programmer or user to change from one data type to
another type in a program. It means a user can easily cast one data to another
according to the requirement in a program.

It does not require checking the compatibility of the variables.

In this casting, we can upgrade or downgrade the data type of one variable to
another in a program.

It uses the cast () operator to change the type of a variable.

Syntax : (type) expression;


1. int num;
2. num = (int ) 4.534; / / cast into int data type
3. cout < < num;
4. #include <iostream>
5. using namespace std;
6. int main ()
7. {
8. // declaration of the variables
9. int a, b;
10. float res;
11. a = 21;
12. b = 5;
13. cout << " Implicit Type Casting: " << endl;
14. cout << " Result: " << a / b << endl; // it loses some information
15.
16. cout << " \n Explicit Type Casting: " << endl;
17. // use cast () operator to convert int data to float
18. res = (float) 21 / 5;
19. cout << " The value of float variable (res): " << res << endl;
20.
21. return 0;
22. }

Output:

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

Implicit Type Casting:


Result: 4

Explicit Type Casting:


The value of float variable (res): 4.2

C++ Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

Functions are used to perform certain actions, and they are important for reusing
code: Define the code once, and use it many times.

Floating point constants or Real constants : The numbers with fractional parts
are called real constants. Decimal notation: 1234.56, 75.098, 0.0002, -0.00674.

Character constants:-

Single character constants: It is character(or any symbol or digit) enclosed within


single quotes.

Ex: „a‟ „1‟ „*‟

Every Character constants have integer values known as ASCII values

Create a Function

C++ provides some pre-defined functions, such as main(), which is used to execute
code. But you can also create your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the


function, followed by parentheses ():

void myFunction(){
// code to be executed
}

Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value.
 inside the function (the body), add code that defines what the function
should do

Call a Function

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

Declared functions are not executed immediately. They are "saved for later use",
and will be executed later, when they are called.

To call a function, write the function's name followed by two parentheses () and a
semicolon ;

In the following example, myFunction() is used to print a text (the action), when it
is called:

Example

Inside main, call myFunction():

// Create a function
void myFunction() {
cout << "I just got executed!";
}

int main() {
myFunction(); // call the function
return 0;
}

N Call by value Call by reference


o.

1 A copy of value is passed to the An address of value is passed to the


function function
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
4 #include <iostream> #include<iostream>
using namespace std; using namespace std;
void change(int data); void swap(int *x, int *y) {
int main() { int swap;
int data = 3; swap=*x;
change(data); *x=*y;
cout << "Value of the data is: " << data *y=swap; }
<< endl; int main() {
return 0; } int x=500, y=100;
void change(int data) { 10. swap(&x, &y); // passing value to f

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

10. data = 5; } unction


Output 11. cout<<"Value of x is: "<<x<<endl;
Value of the data is: 3 12. cout<<"Value of y is: "<<y<<endl;
13. return 0; }
14. Output
Value of x is: 100
Value of y is: 500

Inline function

If make a function as inline, then the compiler replaces the function calling
location with the definition of the inline function at compile time.

Any changes made to an inline function will require the inline function to be
recompiled again because the compiler would need to replace all the code with a
new code; otherwise, it will execute the old functionality.

Syntax for an inline function:

1. inline return_type function_name(parameters)


2. {
3. // function code?
4. }

Inside the main() method, when the function fun1() is called, the control is
transferred to the definition of the called function. The addresses from where the
function is called and the definition of the function are different. This control
transfer takes a lot of time and increases the overhead.

When the inline function is encountered, then the definition of the function is
copied to it. In this case, there is no control transfer which saves a lot of time and
also decreases the overhead.

Let's understand through an example.

1. #include <iostream>
2. using namespace std;
3. inline int add(int a, int b) {
4. return(a+b); }
5. int main() {
6. cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
7. return 0; }

Once the compilation is done, the code would be like as shown as below:

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

1. #include<iostream>
2. using namespace std;
3. inline int add(int a, int b) {
4. return(a+b); }
5. int main() {
6. cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
7. return 0; }

We cannot provide the inlining to the functions in the following circumstances:

o If a function is recursive.
o If a function contains a loop like for, while, do-while loop.
o If a function contains static variables.
o If a function contains a switch or go to statement

When do we require an inline function?

An inline function can be used in the following scenarios:

o An inline function can be used when the performance is required.


o It can be used over the macros.
o We can use the inline function outside the class so that we can hide the
internal implementation of the function.

Advantages of inline function


o In the inline function, we do not need to call a function, so it does not cause
any overhead.
o It also saves the overhead of the return statement from a function.
o It does not require any stack on which we can push or pop the variables as it
does not perform any function calling.
o An inline function is mainly beneficial for the embedded systems as it yields
less code than a normal function.

Disadvantages of inline function

The following are the disadvantages of an inline function:

o The variables that are created inside the inline function will consume
additional registers.
o If we use many inline functions, then the binary executable file also becomes
large.
o The use of so many inline functions can reduce the instruction cache hit rate,
reducing the speed of instruction fetch from the cache memory to that of the
primary memory.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

o It also increases the compile-time overhead because whenever the changes


are made inside the inline function, then the code needs to be recompiled
again to reflect the changes; otherwise, it will execute the old functionality.
o Sometimes inline functions are not useful for many embedded systems
because, in some cases, the size of the embedded is considered more
important than the speed.

Difference between inline and macro


1. Inline :
An inline function is a normal function that is defined by the inline keyword. An
inline function is a short function that is expanded by the compiler. And its
arguments are evaluated only once. An inline functions are the short length
functions that are automatically made the inline functions without using
the inline keyword inside the class.
Syntax of an Inline function:
inline return_type function_name ( parameters )
{ // inline function code}
Example of an Inline function:

#include <iostream>

using namespace std;

// Inline function

inline int Maximum(int a, int b){ return (a > b) ? a : b;}

int main(){

cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;

cout << "Max (20, 0): " << Maximum(20, 0) << endl;

return 0;}

Output:
Max (100, 1000): 1000
Max (20, 0): 20
2. Macro :
It is also called preprocessors directive. The macros are defined by
the #define keyword. Before the program compilation, the preprocessor examines
the program whenever the preprocessor detects the macros then preprocessor
replaces the macro by the macro definition.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

Syntax of Macro:

#define MACRO_NAME Macro_definition

Example of Macro:

#include <iostream>

using namespace std;

// macro with parameter

#define MAXIMUM(a, b) (a > b) ? a : b

int main(){

cout << "Max (100, 1000):";

int k = MAXIMUM(100, 1000);

cout << k << endl;

cout << "Max (20, 0):";

int k1 = MAXIMUM(20, 0);

cout << k1;

return 0;}

Output:
Max (100, 1000):1000
Max (20, 0):20

Difference between Inline and Macro in C++ :


S.NO Inline Macro

An inline function is defined by Whereas the macros are defined by


1. the inline keyword. the #define keyword.

Through inline function, the class’s Whereas macro can’t access the class’s
2. data members can be accessed. data members.

3. In the case of inline function, the Whereas in the case of macros, the

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

S.NO Inline Macro

program can be easily debugged. program can’t be easily debugged.

Whereas in the case of macro, the


In the case of inline, the arguments arguments are evaluated every time
4. are evaluated only once. whenever macro is used in the program.

In C++, inline may be defined either Whereas the macro is all the time
5. inside the class or outside the class. defined at the beginning of the program.

In C++, inside the class, the short


length functions are automatically
6. made the inline functions. While the macro is specifically defined.

Inline is not as widely used as


7. macros. While the macro is widely used.

Inline is not used in competitive While the macro is very much used in
8. programming. competitive programming.

While the macro is not terminated by


Inline function is terminated by the any symbol, it is terminated by a new
9. curly brace at the end. line.

Friend Class A friend function is a function which is not the member or the class
instead of that it can access private and protected members of the class.
A friend function in C++ is defined as a function that can access private,
protected and public members of a class. The friend function is declared using
the friend keyword inside the body of the class.
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Example 1: Working of friend Function
// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

private: int meter;


friend int addFive(Distance); // friend function
public: Distance() : meter(0) {}
};

// friend function definition


int addFive(Distance d) {
//accessing private members from the friend function
d.meter += 5;
return d.meter;}
int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;}

Output Distance: 5

Virtual function (runtime polymorphism and dynamic polymorphism)

A virtual function is a member function in the base class that we expect to redefine
in derived classes.

When you refer to derived class object using a pointer of a reference to base class,
you can call a virtual function for that object and can execute the derived class
functions.

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

For example, consider the code below:

class Base {
public:
void print() {
// code
}
};

class Derived : public Base {


public:
void print() {
// code
}
};
Default Arguments
A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the calling function doesn’t provide a
value for the argument. In case any value is passed, the default value is overridden.
1) The following is a simple C++ example to demonstrate the use of default
arguments. Here, we don’t have to write 3 sum functions; only one function works
by using the default values for 3rd and 4th arguments.

// CPP Program to demonstrate Default Arguments


#include <iostream>
using namespace std;

// A function with default arguments,


// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}
// Driver Code
int main()
{ // Statement 1
cout << sum(10, 15) << endl;

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;}
O/P: 25
50
80
2) If function overloading is done containing the default arguments, then we need
to make sure it is not ambiguous to the compiler, otherwise it will throw an error.
// CPP Program to demonstrate Function overloading in
// Default Arguments
#include <iostream>
using namespace std;
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0)
{ return (x + y + z + w);}
int sum(int x, int y, float z = 0, float w = 0)
{ return (x + y + z + w);}
// Driver Code
int main()
{ cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0; }
3) A constructor can contain default parameters as well. A default constructor can
either have no parameters or parameters with default arguments.
// CPP code to demonstrate use of default arguments in
// Constructors
#include <iostream>
using namespace std;
class A { private:
int var = 0;
public: A(int x = 0): var(x){}; // default constructor with one argument

Downloaded by Ananya Dudeja ([email protected])


lOMoARcPSD|27431833

// Note that var(x) is the syntax in c++ to do : "var = x"


void setVar(int s){
var = s; // OR => this->var = s;
return; }
int getVar(){
return var; // OR => return this->var; } };
int main(){ A a(1);
a.setVar(2);
cout << "var = " << a.getVar() << endl;
/* ANOTHER APPROACH:
A *a = new A(1);
a->setVar(2);
cout << "var = " << a->getVar() << endl; */ }

Downloaded by Ananya Dudeja ([email protected])

You might also like