0% found this document useful (0 votes)
13 views45 pages

structures and functions in OOP

Slides on structure and functions of OOP using C++

Uploaded by

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

structures and functions in OOP

Slides on structure and functions of OOP using C++

Uploaded by

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

RECAP

Functions
Functions
• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
• Parameters/ Arguments
– An argument is the data passed at the time of calling a
function while a parameter is a variable defined by a
function that receives a value when the function is called
Functions
Functions
• Function prototype
– Tells compiler argument type and return type of
function
int square( int );
• Function takes an int and returns an int

• Calling/invoking a function
square(x);
– Parentheses used to call function
• Pass argument x
– After finished, passes back result
Functions
Function Definitions
• Format for function definition
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)

Functions
Function Definitions
• Example function
int square( int y )
{

return y * y;
}
• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
• Functions cannot be defined inside other functions

Functions
Example

2 // Creating and using a programmer-defined function.


3 #include <iostream.h>
4
5 int square( int ); // function prototype
6
7 void main()
8 {
9 // loop 10 times and calculate and output
10 // square of x each time
11 for ( int x = 1; x <= 10; x++ )
12 cout << square( x ) << " "; // function call
13
14 cout << endl;
15
16
17 } // end main

Functions
18 // square function definition returns square of an integer
19 int square( int y ) // y is a copy of argument to function
20 {
21 return y * y; // returns square of y as an int
22
23 } // end function square

1 4 9 16 25 36 49 64 81 100

Functions
Function Prototypes
• Function prototype contains
– Function name
– Parameters (number and data type)
– Return type (void if returns nothing)
– Only needed if function definition after function call
• Prototype must match function definition
– Function prototype
double maximum( double, double, double );
– Definition
double maximum( double x, double y, double z )
{

}

Functions
Function Prototypes
• Function signature
– Part of prototype with name and parameters
• double maximum( double, double, double );

Function signature

Functions
Header Files
• Header files contain
– Function prototypes
– Definitions of data types and constants
• Header files ending with .h
– Programmer-defined header files
#include “myheader.h”

• Library header files


#include <math.h>

Functions
Functions
• Call By Value

Copy of data passed to function

Changes to copy do not change original

Prevent unwanted side effects

Functions
Functions
#include <iostream.h>

void funct(int);

void main(void)
{
int x = 10;
funct(x);
cout << “ In main X : “ <<x;
}

void funct(int x)
{
x = 5;
cout << “ In the Function X : “<< x <<endl;
}

Functions
Functions
• Call by reference
– Function can directly access data
– Changes affect original

Functions
Functions
#include <iostream.h>

void swap(int &, int &);

void main()
{
int x = 10;
int y = 15;
cout << “X : “ << x << “ Y: “ << y << endl;

swap(x,y);
cout << “X : “ << x << “ Y: “ << y << endl;
}

void swap(int &x,int &y)


{
int temp = x;
x = y;
y = temp;
}

Functions
Inline Functions
• Inline functions
– Keyword inline before function
– Asks the compiler to copy code into program instead of
making function call
• Reduce function-call overhead
– Good for small, often-used functions
• Example
inline double cube( double s )
{ return s * s * s; }

Functions
Overloaded Functions
• Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• E.g. function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• Overloaded functions distinguished by signature
– Based on name and parameter types (order matters)

Functions
2 // Using overloaded functions.
3 #include <iostream.h>
4
5 // function square for int values
6 int square( int x )
7 {
8 cout << "Called square with int argument: " << x << endl;
9 return x * x;
10
11 } // end int version of function square
12
13 // function square for double values
13 double square( double y )
15 {
16 cout << "Called square with double argument: " << y << endl;
17 return y * y;
18
19 } // end double version of function square
20

Functions
21 void main()
22 {
23 int intResult = square( 7 ); // calls int version
24 double doubleResult = square( 7.5 ); // calls double version
25
26 cout << "\nThe square of integer 7 is " << intResult
27 << "\nThe square of double 7.5 is " << doubleResult
28 << endl;
29
30
31 } // end main

Called square with int argument: 7


Called square with double argument: 7.5

The square of integer 7 is 49


The square of double 7.5 is 56.25

Functions
Overloaded Functions
• Examples:
int sum(int , int);
int sum (int, int, int);
float sum (int, float);

double multiply (float , float);


Wrong !!!
float multiply (float , float);

Functions
Default Arguments
• Function call with omitted parameters
– If not enough parameters, rightmost go to their defaults
• Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
– myFunction(3)
• x = 3, y and z get defaults (rightmost)
– myFunction(3, 5)
• x = 3, y = 5 and z gets default

Functions
2 // Using default arguments.
3 #include <iostream>
4
5
6 // function prototype that specifies default arguments
7 int boxVolume( int length = 1, int width = 1, int height = 1 );
8
9 void main()
10 {
11 // no arguments--use default values for all dimensions
12 cout << "The default box volume is: " << boxVolume();
13
14 // specify length; default width and height
15 cout << "\n\nThe volume of a box with length 10,\n"
16 << "width 1 and height 1 is: " << boxVolume( 10 );
17
18 // specify length and width; default height
19 cout << "\n\nThe volume of a box with length 10,\n"
20 << "width 5 and height 1 is: " << boxVolume( 10, 5 );
21

Functions
22 // specify all arguments
23 cout << "\n\nThe volume of a box with length 10,\n"
24 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
25 << endl;
26
27
28
29 } // end main
30
31 // function boxVolume calculates the volume of a box
32 int boxVolume( int length, int width, int height )
33 {
34 return length * width * height;
35
36 } // end function boxVolume

The default box volume is: 1

The volume of a box with length 10,


width 1 and height 1 is: 10

The volume of a box with length 10,


width 5 and height 1 is: 50

The volume of a box with length 10,


width 5 and height 2 is: 100
User defined functions
• C++ programs usually have the following form:

// include statements
// function prototypes
// main() function
// function definitions

Functions
Function Input & Output

Functions
Return Value

• A function normally returns a single result, if it is


not a void function.
• At least one of the statements in the function
body should have the form:
return <expression>;
• The value passed back by the return statement
should have the sameFunctions
type as the function.
Passing by Reference
• To have a function with multiple outputs, we
have to use pass by reference.
• We use & to denote a parameter that is
passed by reference: <type>&
• Examples:
void Increment(int&);
void SumAve (double, double,double&, double&);

Functions
Passing by Reference
• The corresponding argument must be a variable.

• The reference of that variable is passed to the


function, instead of its value.

• If the function changes the parameter value, the


change will be reflected in the corresponding
argument, since they share the same memory
location.
Functions
RECAP

Records/Structures

Imran Siddiqi
Dept of CS & SE
Bahria University, Islamabad
[email protected]
Records
Recall that elements of arrays must all be
of the same type

scores
scores:: 85
85 79
79 92
92 57
57 68
68 80
80 ......
0 1 2 3 4 5 98 99
In some situations, we wish to group
elements of different types

employee
employee R.
R.Jones
Jones 123
123Elm
Elm 6/12/55
6/12/55 $14.75
$14.75

Introduction to Programming
Records
• RECORDS are used to group related
components of different types
• Components of the record are called fields
employee
employee R.
R.Jones
Jones 123
123Elm
Elm 6/12/55
6/12/55 $14.75
$14.75

• In C++
– Record called a struct (structure)
– Fields called members

Introduction to Programming
Structures
• Structures hold data that belong together.
• Examples:
– Student record: student id, name, major, gender, start
year
– Bank account: account number, name, currency,
balance
– Address book: name, address, telephone number

• In database applications, structures are called


records.
Introduction to Programming
Structures
• Collection of Variables
• Variables – Different Types
• A simple Structure
struct part
{
int modelNumer;
int partNumber;
float cost;
};
Structures
#include<iostream.h>

struct part
{
int modelNumber;
int partNumber;
float cost;
};

void main(void)
{
part p;
p.modelNumber = 6452;
p.partNumber = 345;
p.cost = 23.45;

cout<<“Model : “ << p.modelNumber << endl;


cout<<“Part : “ << p.partNumber << endl;
cout<<“Cost : “ << p.cost <<endl;

}
Structure
• Specifying the Structure:
Keyword struct Structure Name

struct part
{
int modelNumer; Strucutre Members
int partNumber;
float cost;
};
Size???

Semicolon terminates Specifier


Structures
struct StudentInfo{
int Id; The “StudentInfo”
int age; structure has 4 members
char Gender; of different types.
double CGA;
};

struct StudentGrade{
char Name[15]; The “StudentGrade”
char Course[9]; structure has 5
int Lab[5];
int Homework[3];
members of
int Exam[2]; }; different array types.

Introduction to Programming
Structures
• Defining Structure Variable
– part p;
• Accessing Structure Members
– p.modelNumber;
– p.cost;
• Combining Specifier and Definition
Structures
#include<iostream.h>

struct part
{
int modelNumber;
int partNumber;
float cost;
}p; Combined Specifier
And Definition
void main(void)
{
p.modelNumber = 6452;
p.partNumber = 345;
p.cost = 23.45;

cout<<“Model : “ << p.modelNumber << endl;


cout<<“Part : “ << p.partNumber << endl;
cout<<“Cost : “ << p.cost <<endl;

}
Structures
• Initializing Structure Members
struct part
{
int modelNumer;
int partNumber;
float cost;
};

main()
{
……………………

part p1 = {1234,45,55.45}
……………………
……………………
part p2 = p1;

}
Structures
#include<iostream.h>

struct part
{
int modelNumber;
int partNumber;
float cost;
};

void main(void)
{
part p1 = {6452,345,23.45};

cout<<“Model : “ << p1.modelNumber << endl;


cout<<“Part : “ << p1.partNumber << endl;
cout<<“Cost : “ << p1.cost <<endl;

part p2 = p1;

cout<<“Model : “ << p2.modelNumber << endl;


cout<<“Part : “ << p2.partNumber << endl;
cout<<“Cost : “ << p2.cost <<endl;

}
Structures
Direct assignment operator
Direct relational operators
Direct arithmetic operators

student3 = student1 + student2;

if (student1 < student2)


cout << ...;
Structures
• Structures Within Structures
struct Distance
{
int feet;
float inches;
};

struct Room
{
Distance length;
Distance width;
};
Structures
struct Distance
{
int feet;
float inches;
};

struct Room
{
Distance length;
Distance width;
};
void main(void)
{
Room dinning;
dinning.length.feet = 13;
dinning.length.inches = 6.5;
dinning.width.feet = 10;
dinning.width.inches= 0.5
}
Arrays of Structures
• First declare a struct (such as student)
• Then specify an array of that type
Student stlist [50];

• Access elements of the array, elements of the


Howstruct
do we for (x = 0; x <50; x++)
print all the cout << _______________________;
stlist[x].name
name fields?

Introduction to Programming
Passing Structures to Function
struct part cin>>p1.cost;
{ display(p1);
char partName[10]; }
int partNumber;
float cost; void display (part p2)
}; {
void display(part); cout<<p2.partName;
void main() cout<<p2.partNumber;
{ cout<<p2.cost;
part p1; }
cin>>p1.partName;
cin>>p1.partNumber;

Introduction to Programming
Returning Structure Variables
Like normal variables, you can also return the structure variables as a returning
value of the function.

part p1,p2;
p1= GetS(); // function calling

//////////////////////////////////////////////////

part GetS() //function definition


{
part p3={“abc”, 25, 1000.0};
return p3;
}

Introduction to Programming

You might also like