Presentation is loading. Please wait.

Presentation is loading. Please wait.

Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Introduction to C++ Part II.

Similar presentations


Presentation on theme: "Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Introduction to C++ Part II."— Presentation transcript:

1 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Introduction to C++ Part II

2 Topics Objectives Defining class with a member function Defining a member function with a parameter Data member, set function and get function Initializing objects with constructors Placing Class in a separate file for reusability Software reusability  Separating Interface from Implementation

3 Objectives How to define a class and use it to create an object? How to implement a class’s behaviors as member function? How to implement class’s attributes as a data member? How to call a member function of an object to perform a task? How to use constructor to initialize an object’s data when object is created? How to use object of class string ?

4 An example that consists of class GradeBook  Define a GradeBook object. Function main uses this object and its member function.  Member Function displayMessage() display a message on the screen Defining a Class with a Member Function

5 GradeBook Class

6 GradeBook Object

7 The GradeBook class definition begins with keyword class  Contains a member function called displayMessage Make an object of class GradeBook  Call its displayMessage member function Function main is always called automatically when you execute a program.  Call member function displayMessage explicitly to tell it to perform its task. Defining a Class with a Member Function (Cont.)

8 The access-specifier label public: contains t he keyword public is an access specifier.  Indicates that the function is “available to the public” can be called by other functions in the program (such as main ) by member functions of other classes (if there are any).  Access specifiers are always followed by a colon ( : ).

9 Defining a Member Function with Parameter class GradeBook with a display-Message member function  displays the course name as part of the welcome message.  The new version of displayMessage requires a parameter ( courseName ) that represents the course name to output. A variable of type string represents a string of characters. A string is actually an object of the C++ Standard Library class string.  Defined in header file and part of namespace std.  For now, you can think of string variables like variables of other types such as int.

10 Defining a Member Function with Parameter (Cont.)

11

12 Output

13 Defining a Member Function with Parameter Library function getline reads a line of text into a string. The function call getline( cin, nameOfCourse )  reads characters from the standard input stream object cin (i.e., the keyboard).  places the characters in the string variable nameOfCourse The header file must be included in the program to use function getline.

14 An object has attributes that are carried with it as it’s used in a program.  Such attributes exist throughout the life of the object.  A class normally consists of one or more member functions manipulate the attributes Attributes are represented as variables in a class definition.  Such variables are called data members  Declared inside a class definition but outside the bodies of the class’s member-function definitions. Each object of a class maintains its own copy of its attributes in memory. Defining Data Members

15 Data Members, set Functions and get Functions (cont.)

16

17

18 Most data-member declarations appear after the access- specifier label private: Like public, keyword private is an access specifier. Variables or functions declared after access specifier private are accessible only to member functions of the class. The default access for class members is private  so all members after the class header and before the first access specifier are private. Private Data Members and Functions

19 Points to remember Generally data members should be declared private and member functions should be declared public. An attempt by a function, which is not a member of a particular class (or a friend of that class) to access a private member of that class is a compilation error

20 Declaring data members with access specifier private is known as data hiding. When a program creates (instantiates) an object,  its data members are encapsulated (hidden) in the object.  accessed only by member functions of the object’s class. Data Members (cont.)

21 A client of an object  any class or function that calls the object’s member functions from outside the object.  Calls the class’s public member functions to request the class’s services.  Statements in main call member functions setCourseName, getCourseName and displayMessage on a GradeBook object. Classes often provide public member functions to allow clients of the class to set (i.e., assign values to) or get (i.e., obtain the values of) private data members.  These member function names need not begin with set or get. Set functions are also sometimes called mutators  mutate, or change, values Get functions are also sometimes called accessors  access values Mutators and Accessors

22 Each class can provide a constructor  used to initialize an object of the class when the object is created. A constructor is a special member function that must be defined with the same name as the class  compiler can distinguish it from the class’s other member functions. An important difference between constructors and other functions  constructors cannot return values, so they cannot specify a return type (not even void ). Normally, constructors are declared public. Initializing Objects with Constructor

23 C++ requires a constructor call for each object that is created  helps ensure that each object is initialized before it’s used in a program. The constructor call occurs implicitly when the object is created. If a class does not explicitly include a constructor  the compiler provides a default constructor. a constructor with no parameters.

24 Initializing Objects with Constructor

25

26

27 A constructor specifies in its parameter list the data it requires to perform its task. When you create a new object, you place this data in the parentheses that follow the object name. Constructor’s body passes the constructor’s parameter name to member function setCourseName  simply assigns the value of its parameter to data member courseName.

28 Initializing Objects with Constructor Creates and initializes a GradeBook object called gradeBook1.  the GradeBook constructor is called (implicitly by C++) with the argument "CS101 Introduction to C++ Programming"  initialize gradeBook1 ’s course name.

29 Initializing Objects with Constructor Any constructor that takes no arguments is called a default constructor. A class gets a default constructor in one of two ways:  The compiler implicitly creates a default constructor in a class that does not define a constructor. Such a constructor does not initialize the class’s data members, but does call the default constructor for each data member An uninitialized variable typically contains a “garbage” value.  You explicitly define a constructor that takes no arguments. Such a default constructor will call the default constructor for each data member Perform additional initialization specified by you. If you define a constructor with arguments, C++ will not implicitly create a default constructor for that class.

30 Observations Data members can be initialized in a constructor. Their values may be set later after the object is created. Good software engineering practice  An object is fully initialized before the client code invokes the object’s member functions.  We should not rely on client code to ensure that an object gets initialized properly.

31 One of the benefits of creating class definitions  classes can be reused by programmers.  potentially worldwide. Programmers who wish to use our GradeBook class cannot simply include the file in another program.  function main begins the execution of every program,  every program must have exactly one main function. Placing a Class in a Separate File for Reusability

32 Previous examples consists of a single.cpp file, known as a source-code file,  Contains a GradeBook class definition and  a main function. In an object-oriented C++ program  define reusable source code (such as a class) in a file that by convention has a.h filename extension  known as a header file. Programs use #include preprocessor directives to include header files  take advantage of reusable software components. Placing a Class in a Separate File for Reusability

33 Separates the code into two files  GradeBook.h the header file contains only the GradeBook class definition, the appropriate header files and a using declaration.  XXX.cpp The main function that uses class GradeBook is defined in the source- code file XXX.cpp For the larger programs in industry, we often use a separate source-code file containing function main to test our classes  Known as a driver program. Placing a Class in a Separate File for Reusability

34 Separate header file: GradeBook.h

35

36 Separate source code file: source.cpp

37 A header file such as GradeBook.h cannot be used to begin program execution  It does not contain a main function. To test class GradeBook  Need a separate source-code file containing a main function that instantiates and uses objects of the class. To help the compiler understand how to use a class, explicitly provide the compiler with the class’s definition  For example, to use type string, a program must include the header file.  This enables the compiler to determine the amount of memory that it must reserve for each object of the class. Placing a Class in a Separate File for Reusability

38 The compiler creates only one copy of the class’s member functions  shares that copy among all the class’s objects. Each object, of course, needs its own copy of the class’s data members  contents can vary among objects. The member-function code, however, is not modifiable,  so it can be shared among all objects of the class. The size of an object depends on the amount of memory required to store the class’s data members. Placing a Class in a Separate File for Reusability

39 Now that the class definition is in a header file (without a main function),  we can include that header in any program that needs to reuse our GradeBook class. Placing a Class in a Separate File for Reusability

40 Notice that the name of the GradeBook.h header file in is enclosed in quotes ( " " ) rather than angle brackets ( ).  Normally, a program’s source-code files and user-defined header files are placed in the same directory.  When the preprocessor encounters a header file name in quotes, attempts to locate the header file in the same directory as the file in which the #include directive appears.  If the preprocessor cannot find the header file in that directory, it searches for it in the same location(s) as the C++ Standard Library header files.  When the preprocessor encounters a header file name in angle brackets (e.g., ), it assumes that the header is part of the C++ Standard Library does not look in the directory of the program that is being preprocessed. Placing a Class in a Separate File for Reusability

41 Placing a class definition in a header file reveals the entire implementation of the class to the class’s clients. Conventional software engineering wisdom says that to use an object of a class, the client code needs to know only  what member functions to call,  what arguments to provide to each member function,  what return type to expect from each member function,  client code does not need to know how those functions are implemented. If client code does know how a class is implemented, the client-code programmer might write client code based on the class’s implementation details. Ideally, if that implementation changes, the class’s clients should not have to change. Hiding the class’s implementation details makes it easier  to change the class’s implementation while minimizing, and hopefully eliminating, changes to client code. Separating Interface from Implementation

42 Interfaces define and standardize the ways in which things such as people and systems interact with one another. The interface of a class describes what services a class’s clients can use  how to request those services,  but not how the class carries out the services. A class’s public interface consists of the class’s public member functions (also known as the class’s public services). Separating Interface from Implementation

43 In our prior examples, each class definition contained  the complete definitions of the class’s public member functions and  the declarations of its private data members. It’s better software engineering to define member functions outside the class definition,  Their implementation details can be hidden from the client code.  Ensures that you do not write client code that depends on the class’s implementation details. Separates class GradeBook ’s interface from its implementation by splitting the class definition into two files  the header file GradeBook.h in which class GradeBook is defined,  the source-code file GradeBook.cpp in which GradeBook ’s member functions are defined. Separating Interface from Implementation

44 By convention, member-function definitions are placed in a source-code file of the same base name (e.g., GradeBook ) as the class’s header file but with a.cpp filename extension. This three-file program is composed from the perspectives of  the GradeBook class programmer and  the client-code programmer. Separating Interface from Implementation

45 Header file GradeBook.h is similar to the earlier one,  Only the function definitions are replaced here with function prototypes describe the class’s public interface without revealing the class’s member- function implementations. A function prototype is a declaration of a function that tells the compiler the function’s name, its return type and the types of its parameters. Include the header file GradeBook.h in the client code  provides the compiler with the information it needs to ensure that the client code calls the member functions of class GradeBook correctly. Separating Interface from Implementation

46 Interface of the class (GradeBook.h file)

47 Source-code file GradeBook.cpp defines class GradeBook ’s member functions. Notice that each member-function name in the function headers is preceded by the class name and  ::, which is known as the binary scope resolution operator. This “ties” each member function to the (now separate) GradeBook class definition,  declares the class’s member functions and data members. Implementation of the class

48 Implementation of the class (GradeBook.cpp)

49 Implementation of the class

50 To indicate that the member functions in GradeBook.cpp are part of class GradeBook,  we must first include the GradeBook.h header file. This allows us to access the class name GradeBook in the GradeBook.cpp file. When compiling GradeBook.cpp, the compiler uses the information in GradeBook.h to ensure that  the first line of each member function matches its prototype in the GradeBook.h file,  each member function knows about the class’s data members and other member functions Separating Interface from Implementation

51 Implementation of the client code (main.cpp)

52 Before executing this program, the source-code files must both be compiled, then linked together  the member-function calls in the client code need to be tied to the implementations of the class’s member functions  a job performed by the linker. The diagram shows the compilation and linking process that results in an executable GradeBook application. Separating Interface from Implementation

53

54 The C++ Standard Library is divided into many portions, each with its own header file. The header files contain the function prototypes for the related functions that form each portion of the library. The header files also contain definitions of various class types and functions, as well as constants needed by those functions. A header file “instructs” the compiler on how to interface with library and user-written components. List of some common C++ Standard Library header files. C++ Standard Library Header Files

55 Sometimes functions are not members of a class.  Called global functions. Function prototypes for global functions are placed in header files,  the global functions can be reused in any program The header file provides a collection of functions  enable you to perform common mathematical calculations. Math Library Functions

56

57

58 C++ Standard Library Header

59

60

61

62

63 The element of chance can be introduced into computer applications by using the C++ Standard Library function rand. The function rand generates an unsigned integer between 0 and RAND_MAX  a symbolic constant defined in the header file. The value of RAND_MAX must be at least 32767  the maximum positive value for a two-byte (16-bit) integer. For GNU C++, the value of RAND_MAX is 2147483647  Visual Studio, the value of RAND_MAX is 32767. If rand truly produces integers at random,  every number between 0 and RAND_MAX has an equal chance (or probability) of being chosen each time rand is called. Case Study: Random Number Generation

64 The function prototype for the rand function is in. To produce integers in the range 0 to 5, we use the modulus operator ( % ) with rand : rand() % 6  This is called scaling.  The number 6 is called the scaling factor. Six values are produced. We can shift the range of numbers produced by adding a value. Case Study: Random Number Generation

65

66 Output

67 C++ provides inline functions to help reduce function call overhead  especially for small functions. Placing the qualifier inline before a function’s return type in the function definition “advises” the compiler to generate a copy of the function’s code in place (when appropriate) to avoid a function call. Trade-off  Multiple copies of the function code are inserted in the program (often making the program larger)  Rather than there being a single copy of the function to which control is passed each time the function is called. The complete function definition must appear before the code is inlined so that the compiler knows how to expand a function call into its inlined code. Inline Functions

68 Inline Function

69 It’s possible to declare local and global variables of the same name. C++ provides the unary scope resolution operator ( :: ) to access a global variable when a local variable of the same name is in scope. Using the unary scope resolution operator ( :: ) with a given variable name is optional when the only variable with that name is a global variable. Unary Scope Resolution Operator

70 Example: Unary Scope Resolution Operator

71 Test # 1 Statistics Overall Highest 97 Section 1 Average: 77 (Highest 97) Section 2 Average: 73 (Highest 92) Section 3 Average: 73 (Highest 93) Section 4 Average: 74 (Highest 97) Section 5 Average: 75.50 (Highest 92) Section 6 Average: 70 (Highest 97)

72 Constructors Constructor is a special member function which enables an object to initialize itself when it is created  Name is same as the class name  Invoked whenever an object of its associated class is created  Constructs the values of the data members of the class Destructor is a special member function that destroys the objects when they are no longer required

73 Constructors (Cont.) class integer{ int m,n; public: integer (void); //constructor ……. }; integer :: integer(void){ //constructor defined m = 0; n = 0; } integer int1; // object int1 created

74 Constructors (Cont.) Not only creates the object int1 of type integer  But also initializes its data members m and n to zero.  No need to invoke the constructor function. A constructor that accepts no parameters is called a default constructor  The default constructor for class integer is class integer :: integer();  If no such constructor is defined then compiler supplies a default constructor.

75 Parameterized Constructors class integer{ int m,n; public: integer (int x, int y); //parameterized constructor ……. }; integer :: integer(int x, int y){ //constructor defined m = x; n = y; } integer int1 (10, 100); //must pass the initial values when object int1 is declared; implicit call integer int1 = integer (10, 100); //explicit call

76 Multiple Constructors in a Class integer (); // No arguments integer (int, int); // with arguments class integer{ int m, n; public: integer (){ m = 0; n = 0;} //constructor 1 integer (int a; int b){ m = a; n = b;} //constructor 2 integer (integer & i){ m = i.m; n = i.n;} //constructor 3 }; integer I1; // object I1 created integer I2 (20, 40); // object I2 created integer I3 (I2); // object I3 created  copies the value of I2 into I3  sets the value of every data element of I3 to value of corresponding data elements of I2.  copy constructor

77 Copy Constructor A copy constructor is used to declare and initialize an object from another object  integer I3 (I2)  define object I3 and at the same time initialize it to the values of I2  Another form is: integer I3 = I2; This process of initializing through a copy constructor is known as copy initialization  I3 = I2 ?? Will not invoke the copy constructor However I3 and I2 are objects; the statement is legal and simply assign the values of I2 to I3; member by member. This is the task of overloaded assignment operator ( = )

78 Destructors Used to destroy the objects that have been created by a constructor Like a constructor, the destructor is a member function whose name is the same name as the class name but is preceded by a tilde For example, the destructor for class integer  ~integer(); Destructor never takes any argument nor does it return any values  Invoked implicitly by the compiler upon exit from the program to clean up the storage  Good practice to declare destructors in a program as it releases memory space for future use

79 C++ enables several functions of the same name to be defined, as long as they have different signatures.  This is called function overloading. The C++ compiler selects the proper function to call  examining the number, types and order of the arguments in the call. Overloaded functions are distinguished by their signatures.  A signature is a combination of a function’s name and its parameter types (in order). Function overloading is used to create several functions of the same name  perform similar tasks, but on different data types. Function Overloading

80

81 Example: Function Overloading

82 The elements of an array can be initialized in the array declaration by following the array name  with an equals sign and a brace-delimited comma-separated list of initializers.  An initializer list to initialize an integer array with 10 values. If there are fewer initializers than elements in the array  the remaining array elements are initialized to zero. If the array size is omitted from a declaration with an initializer list,  the compiler determines the number of elements in the array by counting the number of elements in the initializer list. Initializing an Array in a Declaration with an Initializer List

83 Initializer List

84 If the program logic and operations are identical for each data type  overloading may be performed more compactly and conveniently by using function templates. Why Function Templates?

85 All function template definitions begin with the template keyword followed by  a template parameter list to the function template enclosed in angle brackets ( ). Every parameter in the template parameter list is preceded by keyword typename or keyword class. The formal type parameters are placeholders for fundamental types or user-defined types. These placeholders are used to specify the types of the function’s parameters,  to specify the function’s return type and  to declare variables within the body of the function definition. What is Function Template?

86 Example: Function Templates

87

88

89 C++ Standard Library class template vector represents a more robust type of array featuring many additional capabilities. C-style pointer-based arrays have great potential for errors and are not flexible  A program can easily “walk off” either end of an array, because C++ does not check whether subscripts fall outside the range of an array.  Two arrays cannot be meaningfully compared with equality operators or relational operators.  When an array is passed to a general-purpose function designed to handle arrays of any size, the size of the array must be passed as an additional argument.  One array cannot be assigned to another with the assignment operator(s). Class template vector allows you to create a more powerful and less error-prone alternative to arrays. C++ Standard Library Class Template vector

90 The mext program example demonstrates capabilities provided by class template vector.  Those are not available for C-style pointer-based arrays. Standard class template vector is defined in header  belongs to namespace std. C++ Standard Library Class Template vector

91 Example: Template Vector

92

93

94

95

96

97

98

99

100 By default, all the elements of a vector object are set to 0. vector s can be defined to store any data type. vector member function size obtain the number of elements in the vector. You can use square brackets, [], to access the elements in a vector. vector objects can be compared with one another using the equality operators. You can create a new vector object that is initialized with the contents of an existing vector by using its copy constructor. C++ Standard Library Class Template vector

101 You can use the assignment ( = ) operator with vector objects. As with C-style pointer-based arrays, C++ does not perform any bounds checking when vector elements are accessed with square brackets. Standard class template vector provides bounds checking in its member function at  “throws an exception” (Exception Handling) if its argument is an invalid subscript. C++ Standard Library Class Template vector


Download ppt "Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Introduction to C++ Part II."

Similar presentations


Ads by Google