Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece."— Presentation transcript:

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

2 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 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 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 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 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 7 Before we examine classes... We need to talk about functions...

8 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 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 10 Function essentials #define PI 3.14159265 #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 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 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 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 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 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 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 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 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: 5 10 5 The local num hides the definition of the global num

19 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: 13.5 5 13.5 The local num hides the definition of the global num DANGEROUS CODE! DO NOT DO THIS

20 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 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 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: 1 2 3 4 5

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


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

Similar presentations


Ads by Google