Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 3 3 Midterm review Introduction to Classes and Objects.

Similar presentations


Presentation on theme: " 2006 Pearson Education, Inc. All rights reserved. 1 3 3 Midterm review Introduction to Classes and Objects."— Presentation transcript:

1  2006 Pearson Education, Inc. All rights reserved. 1 3 3 Midterm review Introduction to Classes and Objects

2  2006 Pearson Education, Inc. All rights reserved. 2

3 3 Recap A class is an expanded concept of a data structure Instead of only holding data, it can hold data and functions – Gradebook XYZ; Private members of a class are accessible only from within other members of the same class Public members are accessible from anywhere where the object is visible

4 4 Rectangle class class Rectangle { int x, y; public: void set_values (int,int); int area (void); }; Four members, two data members of type int with private access Two member functions with public access We have shown only the declaration not the definition of the functions We can now declare an object of type Rectangle – Rectangle rect;

5 5 Rectangle class rect.set_values (3,4); myarea = rect.area(); After the declaration of rect, we can refer within the body of the program to any of the public members of the object rect as if they were normal functions or variables just by putting the object name followed by dot(.) and followed by the name of the member The only members we cannot access are x and y since they are private

6 6 Rectangle class #include using namespace std; class CRectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void CRectangle::set_values (int a, int b) { x = a; y = b; } int main () { CRectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } Area: 12

7 7 Rectangle class #include using namespace std; class Rectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void Rectangle::set_values (int a, int b) { x = a; y = b; } int main () { Rectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } Area: 12 The operator of scope :: included in the definition of set_values is used to define a member of a class from outside the class definition itself Area is define directly inside. We must use the scope operator to specify that is a member of the class Rectangle and not a global function. This allows the same scope properties as if it was being declared inside the definition

8 8 Rectangle class // example: one class, two objects #include using namespace std; class Rectangle { int x, y; public: void set_values (int,int); int area () {return (x*y);} }; void Rectangle::set_values (int a, int b) { x = a; y = b; } int main () { Rectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Rect area: 12 Rectb area: 30 Each has its own mamber variables and functions This is the main concept of object oriented programming. Data and functions are both members of the object.

9 9 3.7 Initializing Objects with Constructors Objects generally need to initialize variables or initialize dynamic memory once they are created For example in the previous example, if we called the function area without calling setvalues first? A class can include a special function called constructor – Functions used to initialize an object’s data when it is created Call made implicitly when object is created Must be defined with the same name as the class Cannot return values – Not even void – Default constructor has no parameters The compiler will provide one when a class does not explicitly include a constructor – Compiler’s default constructor only calls constructors of data members that are objects of classes

10 10 3.7 Initializing Objects with Constructors // example: class constructor #include using namespace std; class CRectangle { int width, height; public: CRectangle (int,int); int area () {return (width*height);} }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Constructors cannot be called explicitly as if they were regular member functions.

11 11 Default constructors If no constructor is given, the compiler assumes the class to have a default with no arguments

12  2006 Pearson Education, Inc. All rights reserved. 12 Outline fig03_07.cpp (1 of 3) Constructor has same name as class and no return type Initialize data member

13  2006 Pearson Education, Inc. All rights reserved. 13 Outline fig03_07.cpp (2 of 3)

14  2006 Pearson Education, Inc. All rights reserved. 14 Outline fig03_07.cpp (3 of 3) Creating objects implicitly calls the constructor

15  2006 Pearson Education, Inc. All rights reserved. 15 Error-Prevention Tip 3.2 Unless no initialization of your class’s data members is necessary (almost never), provide a constructor to ensure that your class’s data members are initialized with meaningful values when each new object of your class is created.

16  2006 Pearson Education, Inc. All rights reserved. 16 Software Engineering Observation 3.5 Data members can be initialized in a constructor of the class or their values may be set later after the object is created. However, it is a good software engineering practice to ensure that an object is fully initialized before the client code invokes the object’s member functions. In general, you should not rely on the client code to ensure that an object gets initialized properly.

17 17 3.8 Placing a Class in a Separate File for Reusability.cpp file is known as a source-code file Header files – Separate files in which class definitions are placed Allow compiler to recognize the classes when used elsewhere – Generally have.h filename extensions Driver files – Program used to test software (such as classes) – Contains a main function so it can be executed

18  2006 Pearson Education, Inc. All rights reserved. 18 Outline fig03_09.cpp (1 of 2) Class definition is in a header file

19  2006 Pearson Education, Inc. All rights reserved. 19 Outline fig03_09.cpp (2 of 2)

20  2006 Pearson Education, Inc. All rights reserved. 20 Outline fig03_10.cpp (1 of 1) Including the header file causes the class definition to be copied into the file

21 21 3.8 Placing a Class in a Separate File for Reusability (Cont.) #include preprocessor directive – Used to include header files Instructs C++ preprocessor to replace directive with a copy of the contents of the specified file – Quotes indicate user-defined header files Preprocessor first looks in current directory – If the file is not found, looks in C++ Standard Library directory – Angle brackets indicate C++ Standard Library Preprocessor looks only in C++ Standard Library directory

22 22 3.8 Placing a Class in a Separate File for Reusability (Cont.) Creating objects – Compiler must know size of object C++ objects typically contain only data members Compiler creates one copy of class’s member functions – This copy is shared among all the class’s objects

23  2006 Pearson Education, Inc. All rights reserved. 23 Error-Prevention Tip 3.3 To ensure that the preprocessor can locate header files correctly, #include preprocessor directives should place the names of user-defined header files in quotes (e.g., "GradeBook.h" ) and place the names of C++ Standard Library header files in angle brackets (e.g., ).

24 24 3.9 Separating Interface from Implementation Interface – Describes what services a class’s clients can use and how to request those services But does not reveal how the class carries out the services A class definition that lists only member function names, return types and parameter types – Function prototypes – A class’s interface consists of the class’s public member functions (services) Separating interface from implementation – Client code should not break if implementation changes, as long as interface stays the same

25 25 3.9 Separating Interface from Implementation (Cont.) Separating interface from implementation (Cont.) – Define member functions outside the class definition, in a separate source-code file In source-code file for a class – Use binary scope resolution operator ( :: ) to tie each member function to the class definition Implementation details are hidden – Client code does not need to know the implementation – In header file for a class Function prototypes describe the class’s public interface

26  2006 Pearson Education, Inc. All rights reserved. 26 Outline fig03_11.cpp (1 of 1) Interface contains data members and member function prototypes

27  2006 Pearson Education, Inc. All rights reserved. 27 Common Programming Error 3.8 Forgetting the semicolon at the end of a function prototype is a syntax error.

28  2006 Pearson Education, Inc. All rights reserved. 28 Good Programming Practice 3.7 Although parameter names in function prototypes are optional (they are ignored by the compiler), many programmers use these names for documentation purposes.

29  2006 Pearson Education, Inc. All rights reserved. 29 Error-Prevention Tip 3.4 Parameter names in a function prototype (which, again, are ignored by the compiler) can be misleading if wrong or confusing names are used. For this reason, many programmers create function prototypes by copying the first line of the corresponding function definitions (when the source code for the functions is available), then appending a semicolon to the end of each prototype.

30  2006 Pearson Education, Inc. All rights reserved. 30 Common Programming Error 3.9 When defining a class’s member functions outside that class, omitting the class name and binary scope resolution operator ( :: ) preceding the function names causes compilation errors.

31  2006 Pearson Education, Inc. All rights reserved. 31 Outline fig03_12.cpp (1 of 2) Binary scope resolution operator ties a function to its class GradeBook implementation is placed in a separate source-code file Include the header file to access the class name GradeBook

32  2006 Pearson Education, Inc. All rights reserved. 32 Outline fig03_12.cpp (2 of 2)

33  2006 Pearson Education, Inc. All rights reserved. 33 Outline fig03_13.cpp (1 of 1)

34 34 3.9 Separating Interface from Implementation (Cont.) The Compilation and Linking Process – Source-code file is compiled to create the class’s object code (source-code file must #include header file) Class implementation programmer only needs to provide header file and object code to client – Client must #include header file in their own code So compiler can ensure that the main function creates and manipulates objects of the class correctly – To create executable application Object code for client code must be linked with the object code for the class and the object code for any C++ Standard Library object code used in the application

35 35 Dynamic Memory allocation What if we need a variable amount of memory that can only be determined at run-time We use the new operator to request dynamic memory new is followed by a data type specifier – int * temp; – temp = new int[5]; – The system dynamically assigns space for 5 elements of type int and returns the pointer to the first element of the sequence – The first element can now be either accessed as temp[0] or * temp – Different from array Size of array has to be a constant This can be a variable

36 36 Dynamic Memory allocation Dynamic memory is allocated from the memory heap, however resources are scarce We have to have a way to make sure if the request for memory was successful or not Two standard methods – Exceptions (later) – nothrow(), the pointer returned by null is a null pointer int * temp; temp = new (nothrow) int [5]; if (temp ==0) { // error assigning memory, take measures }

37 37 Dynamic Memory allocation Once the need for dynamic memory is over, it should be freed so that memory becomes available again We use the delete operator for this The value passed as argument to delete must be either a pointer to a memory block previously allocated by new or a null pointer Delete pointer Delete [] pointer

38 38 Matrix class We will be making a simple matrix class in the lab Private members of the matrix class – How to store values – Rows, columns Constructor/ destructor Addition Subtraction Multiplication Operator overloading – Assignment operator

39 39 Destructor The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using the operator delete. The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value.

40 40 // example on constructors and destructors #include using namespace std; class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () {return (*width * *height);} }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }

41 41 Overloading provides concise notation – object2 = object1.add( object2 ); vs. object2 = object2 + object1; Operator overloading


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 3 3 Midterm review Introduction to Classes and Objects."

Similar presentations


Ads by Google