Programming in C++ 1. Learning Outcome  At the end of this slide, student able to:  Understand the usage of classes and functions.  Understand static.

Slides:



Advertisements
Similar presentations
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Advertisements

Chapter 10 THINKING IN OBJECTS 1 Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 5 Functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 5 Function Basics.
Road Map Introduction to object oriented programming. Classes
Introduction to Java Programming, 4E Y. Daniel Liang.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
METHODS Introduction to Systems Programming - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 6 Functions 1. Opening Problem 2 Find the sum of integers from 1 to 10, from 20 to 37, and from 35 to 49, respectively.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Chapter 5 Classes and Objects §5.1 Specifying a class §5.2 Defining Member Functions §5.3 Memory Allocation and Static Members §5.4 Passing Objects to/from.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
1 Introducing Methods A method is a collection of statements that are grouped together to perform an operation.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
1.  At the end of this slide, student able to:  Object-Oriented Programming  Research on OOP features.  Do a code walkthrough to examine the implementation.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 6 Functions.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Objects and Classes.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
1 COS240 O-O Languages AUBG, COS dept Lecture 12 Title: Java Classes and Objects Reference: COS240 Syllabus.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 5 Methods.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 10 More on Objects and Classes.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Chapter 9 Objects and Classes §9.1 Introduction §9.2 Defining Classes and Objects §9.3 Access Objects §9.4 Separating Declaration from Implementation §9.5.
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods Dr. Musab Zghoul.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 5 Functions Lecturer: Mrs Rohani Hassan.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Methods.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
Chapter 9 More on Objects and Classes
A First C++ Class – a Circle
Chapter 5 Function Basics
Chapter 6: Methods CS1: Java Programming Colorado State University
Chapter 6 Functions.
Chapter 5 Functions DDC 2133 Programming II.
Chapter 5 Function Basics
Chapter 5 Functions.
Chapter 6 Methods 1.
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 5 Function Basics
Group Status Project Status.
Chapter 9 Objects and Classes
Chapter 6 Methods.
Chapter 5 Methods.
Object Oriented Programming in java
OO Programming Concepts
Lecture 8 Object Oriented Programming (OOP)
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Programming in C++ 1

Learning Outcome  At the end of this slide, student able to:  Understand the usage of classes and functions.  Understand static member data 2

3 Classes Classes are constructs that define objects of the same type. A class uses variables to define data fields and functions to define behaviors. Additionally, a class provides a special type of functions, known as constructors, which are invoked to construct objects from the class.

4 Classes

5 UML Class Diagram

6 A Simple Circle Class  Objective: Demonstrate creating objects, accessing data, and using functions. TestCircle Run

7 Constructors The constructor has exactly the same name as the defining class. Like regular functions, constructors can be overloaded (i.e., multiple constructors with the same name but different signatures), making it easy to construct objects with different initial data values. A class normally provides a constructor without arguments (e.g., Circle()). Such constructor is called a no-arg or no-argument constructor. A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class.

8 Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors play the role of initializing objects.

9 Object Names In C++, you can assign a name when creating an object. A constructor is invoked when an object is created. The syntax to create an object using the no-arg constructor is ClassName variableName; For example, Circle circle1;

10 Constructing with Arguments The syntax to declare an object using a constructor with arguments is ClassName variableName(arguments); For example, the following declaration creates an object named circle2 by invoking the Circle class’s constructor with a specified radius 5.5. Circle circle2(5.5);

11 Access Operator After an object is created, its data can be accessed and its functions invoked using the dot operator (.), also known as the object member access operator: objectName.dataField references a data field in the object. objectName.function(arguments) invokes a function on the object.

12 Naming Objects and Classes When you declare a custom class, capitalize the first letter of each word in a class name; for example, the class names Circle, Rectangle, and Desk. The class names in the C++ library are named in lowercase. The objects are named like variables.

13 Class is a Type You can use primitive data types to define variables. You can also use class names to declare object names. In this sense, a class is also a data type.

14 Memberwise Copy In C++, you can also use the assignment operator = to copy the contents from one object to the other. By default, each data field of one object is copied to its counterpart in the other object. For example, circle2 = circle1; copies the radius in circle1 to circle2. After the copy, circle1 and circle2 are still two different objects, but with the same radius.

15 Constant Object Name Object names are like array names. Once an object name is declared, it represents an object. It cannot be reassigned to represent another object. In this sense, an object name is a constant, though the contents of the object may change.

16 Anonymous Object Most of the time, you create a named object and later access the members of the object through its name. Occasionally, you may create an object and use it only once. In this case, you don’t have to name the object. Such objects are called anonymous objects. The syntax to create an anonymous object using the no-arg constructor is ClassName() The syntax to create an anonymous object using the constructor with arguments is ClassName(arguements)

17 Class Replaces struct The C language has the struct type for representing records. For example, you may define a struct type for representing students as shown in (a).

18 Separating Declaration from Implementation C++ allows you to separate class declaration from implementation. The class declaration describes the contract of the class and the class implementation implements the contract. The class declaration simply lists all the data fields, constructor prototypes, and the function prototypes. The class implementation implements the constructors and functions. The class declaration and implementation are in two separate files. Both files should have the same name, but with different extension names. The class declaration file has an extension name.h and the class implementation file has an extension name.cpp. Circle.h Run Circle.cpp TestCircleWithDeclaration.cpp

19 Preventing Multiple Declarations It is a common mistake to include the same header file in a program multiple times inadvertently. Suppose Head1.h includes Circle.h and TestHead1.cpp includes both Head1.h and Circle.h, as shown in Listings 9.5 and 9.6.

20 Preventing Multiple Declarations #include "Circle.h" // Other code in Head1.h omitted #include "Circle.h" #include "Head1.h" int main() { // Other code in Head2.h omitted } Head1.h TestHead1.cpp

21 inclusion guard #ifndef CIRCLE_H #define CIRCLE_H class Circle { public: // The radius of this circle double radius; // Construct a default circle object Circle(); // Construct a circle object Circle(double); // Return the area of this circle double getArea();Semicolon required }; #endif

22 Inline Declaration §6.6, “Inline Functions,” introduced how to improve function efficiency using inline functions. Inline functions play an important role in class declarations. When a function is implemented inside a class declaration, it automatically becomes an inline function. This is also known as inline declaration.

23 Inline Declaration Example For example, in the following declaration for class A, the constructor and function f1 are automatically inline functions, but function f2 is a regular function. class A { public: A() { // do something; } double f1() { // return a number } double f2(); };

24 Inline Functions in Implementation File There is another way to declare inline functions for classes. You may declare inline functions in the class’s implementation file. For example, to declare function f2 as an inline function, precede the inline keyword in the function header as follows: // Implement function as inline inline double A::f2() { // return a number }

25 Inline Declarations? As noted in §5.16, short functions are good candidates for inline functions, but long functions are not.

26 Data Field Encapsulation The data fields radius in the Circle class in Listing 9.1 can be modified directly (e.g., circle1.radius = 5). This is not a good practice for two reasons: F First, data may be tampered. F Second, it makes the class difficult to maintain and vulnerable to bugs. Suppose you want to modify the Circle class to ensure that the radius is non-negative after other programs have already used the class. You have to change not only the Circle class, but also the programs that use the Circle class. Such programs are often referred to as clients. This is because the clients may have modified the radius directly (e.g., myCircle.radius = -5).

27 Accessor and Mutator Colloquially, a get function is referred to as a getter (or accessor), and a set function is referred to as a setter (or mutator). A get function has the following signature: returnType getPropertyName() If the returnType is bool, the get function should be defined as follows by convention: bool isPropertyName() A set function has the following signature: public void setPropertyName(dataType propertyValue)

28 Example: New Circle Class Circle2.h Run Circle2.cpp

29 The Scope of Variables Chapter 5, “Function Basics,” discussed the scope of global variables and local variables. Global variables are declared outside all functions and are accessible to all functions in its scope. The scope of a global variable starts from its declaration and continues to the end of the program. Local variables are defined inside functions. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable.

30 The Scope of Variables The data fields are declared as variables and are accessible to all constructors and functions in the class. In this sense, data fields are like global variables. However, data fields and functions can be declared in any order in a class. For example, all the following declarations are the same:

31 The Scope of Variables Local variables are declared and used inside a function locally. If a local variable has the same name as a data field, the local variable takes precedence and the data field with the same name is hidden. For example, in the following program in Listing 9.8, x is defined as a data field and as a local variable in the function. Run HideDataField

32 Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user.

33 Example: The Loan Class TestLoanClassRunLoan.cppLoan.h

34 Introducing Functions A function is a collection of statements that are grouped together to perform an operation.

35 Introducing Functions, cont. Function signature is the combination of the function name and the parameter list. The variables defined in the function header are known as formal parameters. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

36 Introducing Functions, cont. A Function may return a value. The returnValueType is the data type of the value the function returns. If the function does not return a value, the returnValueType is the keyword void. Void function vs. procedure vs. subroutine

37 Calling Functions Listing 5.1 Testing the max Function This program demonstrates calling a Function max to return the largest of the int values TestMax

38 Calling Functions, cont. animation

39 Trace Function Invocation animation i is now 5

40 Trace Function Invocation animation j is now 2

41 Trace Function Invocation animation invoke max(i, j)

42 Trace Function Invocation animation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

43 Trace Function Invocation animation declare variable result

44 Trace Function Invocation animation (num1 > num2) is true since num1 is 5 and num2 is 2

45 Trace Function Invocation animation result is now 5

46 Trace Function Invocation animation return result, which is 5

47 Trace Function Invocation animation return max(i, j) and assign the return value to k

48 Trace Function Invocation animation Execute the print statement

49 Call Stacks

50 Trace Call Stack i is declared and initialized animation

51 Trace Call Stack animation j is declared and initialized

52 Trace Call Stack animation Declare k

53 Trace Call Stack animation Invoke max(i, j)

54 Trace Call Stack animation pass the values of i and j to num1 and num2

55 Trace Call Stack animation (num1 > num2) is true

56 Trace Call Stack animation Assign num1 to result

57 Trace Call Stack animation Return result and assign it to k

58 Trace Call Stack animation Execute print statement

59 void Functions The preceding section gives an example of a nonvoid function. This section shows how to declare and invoke a void function. Listing 5.2 gives a program that declares a function named printGrade and invokes it to print the grade for a given score. TestVoidFunction TestReturnGradeFunction

60 Modularizing Code Methods can be used to reduce redundant coding and enable code reuse. Methods can also be used to modularize code and improve the quality of the program. GreatestCommonDivisorFunction PrimeNumberFunction

61 Overloading Functions The max function that was used earlier works only with the int data type. But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another function with the same name but different parameters, as shown in the following code: TestFunctionOverloading

62 Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a function, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

63 Ambiguous Invocation #include using namespace std; int maxNumber(int num1, double num2) { if (num1 > num2) return num1; else return num2; } double maxNumber(double num1, int num2) { if (num1 > num2) return num1; else return num2; } int main() { cout << maxNumber(1, 2) << endl; return 0; }

64 Function Prototypes Before a function is called, it must be declared first. One way to ensure it is to place the declaration before all function calls. Another way to approach it is to declare a function prototype before the function is called. A function prototype is a function declaration without implementation. The implementation can be given later in the program. TestFunctionPrototype

65 Reusing Functions by Different Programs One of the benefits of functions is for reuse. In the preceding sections, you declared functions and used them from the same program. To make the functions available for other programs to use, you need to place the functions in a separate file, called header file. By convention, the file has a.h extension. Programs use #include preprocessor directives to include header files in order to reuse the functions defined in the header file. MyLib.hUseMyLib.cpp

66 Case Study: Generating Random Characters Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. As introduced in §2.11, every character has a unique ASCII code between 0 and 127. To generate a random character is to generate a random integer between 0 and 127. You learned how to generate a random number in §3.8. Recall that you can use the srand(seed) function to set a seed and use rand() to return a random integer. You can use it to write a simple expression to generate random numbers in any range. For example,

67 Case Study: Generating Random Characters, cont. RandomCharacter.h TestRandomCharacter

68 Math Functions Run

69 Character Functions

70 Case Conversion Functions CharacterFunctionsRun