1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Functions.
1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
File Review Declare the File Stream Object Name –ofstream for output to file –ifstream for input from file Associate a File Name with the File Stream Object.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Review of C++ Programming Part II Sheng-Fang Huang.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Chapter 6: User-Defined Functions
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Learners Support Publications Classes and Objects.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Object-Oriented Programming (OOP) and C++
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions.
A Lecture for the c++ Course
Classes Object-oriented programming: Example: Bank transactions
FUNCTIONS IN C++.
CSC113: Computer Programming (Theory = 03, Lab = 01)
User-Defined Functions
6 Functions.
Scope, Parameter Passing, Storage Specifiers
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Arrays Kingdom of Saudi Arabia
6 Chapter Functions.
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Variables have attributes
Defining Classes and Methods
Submitted By : Veenu Saini Lecturer (IT)
The Three Attributes of an Identifier
Corresponds with Chapter 5
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece

2 Sneak preview: Classes Problem: Provide a user friendly, "flexible" array that hides the memory allocation operations. Encapsulate the data and operations that are allowed to it Recall: In OOP we model a problem as a collection of objects that have certain attributes and interact with one another and/or the world through specific operations. Object: Our flexible array Attributes: Its size, how full it is... Operations: Insert or remove elements, find out the size, etc.

3 Sneak preview: Classes Class = a blueprint for an object. It describes the object's attributes (member data) and any operations that are allowed on the object (member functions) Example: Bank transactions object: bank account attribute: balance operations: initialize, deposit, withdraw. We need to design a blueprint to describe the bank account. Object = an instance of a class e.g. a specific bank account. The attributes will now have specific values.

4 The bank account class, take 1 class BankAccount { private: int balance; // in dollars public: BankAccount(); void deposit(int amount); void withdraw(int amount); int getBalance(); } ; The name of the class. We will use it to create BankAccount objects.

5 The bank account class, take 1 class BankAccount { private: int balance; // in dollars public: BankAccount(); void deposit(int amount); void withdraw(int amount); int getBalance(); } ; private and public are member access specifiers. Data members or member functions that are declared private cannot be directly accessed outside of the class. Instead, they can only be accessed by member functions. In this example, it is necessary to make the balance private since then it can only be modified in a controlled way through the withdraw and deposit functions. data member

6 The bank account class, take 1 class BankAccount { private: int balance; // in dollars public: BankAccount(); void deposit(int amount); void withdraw(int amount); int getBalance(); } ; Data members or member functions that are declared public can be accessed directly from outside the class. Privacy allows us to separate the interface from the implementation. public members : the interface private members : part of the implementation This allows us to change the implementation without changing the interface. Usually, data are private and functions are public.

7 Before we examine classes... We need to talk about functions...

8 Function essentials C++ library functions Include appropriate header file Call function by name #include using std::cout; using std::endl; int main() { double num = 2.0; cout << "The square root of " << num << " is " << sqrt(num) << endl; return 0; } library of math functions argument (actual parameter)

9 Function essentials User-defined functions Declare a function (= write a function prototype to specify its name, number and types of parameters, type of return value) Define a function (= write the body of the function) Call function by name Syntax return_type function_name (argument_list) ; default is int A list of the types and names of the function's input arguments. Looks like a comma-separated list of variable declarations. Where? Between the preprocessor directives and main, or in header file

10 Function essentials #define PI #include double compute_circle_area(double radius); int main () { double radius, area; std::cout << "Enter the radius in inches: "; std::cin >> radius; area = compute_circle_area(radius); std::cout << "The area is " << area << " inches" << std::endl; return 0; } double compute_circle_area (double radius) { return PI * radius * radius; }

11 Scope Scope of an identifier = the portion of a program where the identifier may be referenced. File scope An identifier declared outside any function has file scope. This means that it can be referenced anywhere within the file. Example 1 : function prototypes Example 2 : global variables Usually declared before main() They may be accessed anywhere in the program Avoid using global variables! They may allow unintended side effects to occur.

12 Example: file scope #include double num; double square(); int main () { num = 2.5; double num_sq = square(); return 0; } double square() { double result = num * num; return result; } Scope of num

13 Scope Block scope An identifier declared within a block (sequence of statements enclosed in curly braces) has block scope. This means that it can be referenced only within the block. Example : local variables Two functions may have local variables with the same name without conflict, since the variables exist in different scopes.

14 Example: block scope #include double square(double); int main () { double num, num_squared; num = 2.5; num_squared = square(num); return 0; } double square(double x) { double num_squared; num_squared = x * x; return num_squared; } Scope of num, num_squared Scope of num_squared completely different variables

15 Example: block scope #include int main () { int x; { int y = 20; } x = y * 2; return 0; } Scope of x Scope of y ERROR! y is out of scope (not visible)

16 Scope Function-prototype scope This applies to the parameters of a function. They are visible only within the function. Other types of scope will be discussed later on. Scope conflicts: If two variables have the same name and their scopes overlap, then the name in the inner scope hides the name in the outer scope. Avoid using duplicate identifiers in a program!

17 Example: scope conflicts #include using std::cout; using std::endl; float num = 10.0; void print_num() { cout << num << endl; } int main () { int num = 5; cout << num << endl; print_num(); return 0; } scope of global num Scope of local num Program output: 5 10 DANGEROUS CODE! DO NOT DO THIS

18 Example: scope conflicts #include using std::cout; using std::endl; int num = 5; void print_magic_num() { int num = 20; cout << num << endl; } int main () { cout << num << endl; print_magic_num(); cout << num << endl; return 0; } scope of global num Scope of local num Program output: The local num hides the definition of the global num

19 Example: scope conflicts #include using std::cout; using std::endl; float num; void print_num() { cout << num << endl; } int main () { num = 13.5; cout << num << endl; int num = 5; cout << num << endl; print_num(); return 0; } scope of global float, num Scope of local int, num Program output: The local num hides the definition of the global num DANGEROUS CODE! DO NOT DO THIS

20 Storage class Storage class of an identifier = the period during which the identifier exists in memory automatic storage The identifier exists only during the execution of the block in which it is defined. This is the default storage for local variables. Storage class: WHEN Scope: WHERE

21 Storage class static storage The identifier exists from the moment the program begins execution. The identifier is bound to storage as the program is compiled. This can allow the value of a local variable to be retained across calls. The local variable must be declared with the keyword 'static' Global variables have static storage.

22 Example: static #include void increment(); int main () { for (int i=0; i<5; i++) increment(); return 0; } void increment() { static int num = 1; std::cout << num++ << std::endl; } Program output:

23 extern If a variable is declared (as a global) in file A and used in file B, the extern keyword is used in file B to tell the compiler that the variable is declared elsewhere: // file proj1.cpp int num_students = 14; // file proj2.cpp void get_class_size () { extern int num_students; cout << num_students; }

24 static vs. extern static is often used when we do not want to allow other files to modify a variable. // file proj1.cpp static int num_students; // num_students can be // used by any function // inside proj1.cpp, but // not outside it. // file proj2.cpp void set_students () { extern int num_students; num_students = 14; } ERROR! There is no non-static global variable by that name.

25 Stack frames A function needs to save information in memory during its execution. For example, it needs to save its local variables and its parameters. This information is grouped together in an area called a "frame" (or "activation record") Storage is organized as a stack (LIFO structure) The stack contains a frame for each active function When a function is called, a new stack frame is created for it and pushed onto the stack. When the function exits, its stack frame is popped.

26 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies do not affect the values of the original variables. Call by reference The caller supplies the address of the actual parameter rather than a copy of its value. This allows the caller to modify the values of the original variables. It is often used when we want to avoid copying "large" data. Using the keyword 'const' allows us to pass values by reference without letting the called function modify them.

27 Example: Call by value #include using std::cout; using std::endl; void print_num (int num); int main () { int x = 4; print_num(x); return 0; } void print_num(int num) { cout << num << endl; } The value of x is copied into num. Program output: 4

28 Example: Call by value #include using std::cout; using std::endl; void update_num (int num); int main () { int num = 4; print_num(num); cout << num << endl; return 0; } void update_num(int num) { num++; cout << num << endl; } Completely different variables that happen to have the same name. They exist in different scopes, so there is no conflict. The value of num is copied into num. The modification of num inside update_num() has no effect on the num defined in main. Program output: 5 4

29 Example: Call by value #include using std::cout; using std::endl; void swap (int a, int b); int main () { int num1 = 4, num2 = 12; swap(num1, num2); cout << num1 << endl << num2 << endl; return 0; } void swap (int a, int b) { int temp = a; a = b; b = temp; } Program output: 4 12 Since num1 and num2 were passed by value, the changes to a and b had no effect on num1 and num2. The numbers have not been swapped.

30 Example: Call by reference #include using std::cout; using std::endl; void swap (int& a, int& b); int main () { int num1 = 4, num2 = 12; swap(num1, num2); cout << num1 << endl << num2 << endl; return 0; } void swap (int& a, int& b) { int temp = a; a = b; b = temp; } Program output: 12 4 This time, the modifications to a and b have affected the values of num1 and num2, because they were performed on the values stored in the addresses of num1 and num2.

31 Example: Call by reference #include using std::cout; void freeze (int& temp); int main () { int temperature; freeze(temperature); cout << temperature; return 0; } void freeze (int& temp) { temp = 32; } Program output: 32 This is an example of using call by reference to initialize a value from inside a called function. It is often used when the called function needs to modify several values and pass them back to the caller.