Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes.

Similar presentations


Presentation on theme: "Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes."— Presentation transcript:

1 Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes

2 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 2 Topics 12.1 Procedural and Object-Oriented Programming 12.2 Introduction to Classes 12.3 Defining an Instance of a Class 12.4 Why Have Private Members? 12.5 Software Design Considerations 12.6 Using Private Member Functions 12.7 Inline Member Functions 12.8 Constructors

3 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 3 Topics 12.9 Destructors 12.10 Constructors That Accept Arguments 12.11 Input Validation Objects 12.12 Overloading Constructors 12.13 Only One Default Constructor and One Destructor 12.14 Arrays of Objects 12.17 An Object-Oriented System Development Primer

4 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 4 12.1 Procedural and Object- Oriented Programming Procedural programming: – focuses on the processes/actions that occur in a program Object-Oriented programming: – is based on the data and the functions that operate on it. Objects are instances of ADTs that represent the data and its functions

5 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 5 Problems with Procedural Programming global variables versus complex function hierarchies Use of global data may allow data corruption Programs based on complex function hierarchies are: –difficult to understand and maintain –difficult to modify and extend –easy to break

6 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 6 Object-Oriented Programming Terminology class: –like a struct (which allows bundling of related variables), but variables and functions in the class can have different properties than in a struct object: –an instance of a class, in the same way that a structure variable is an instance of a struct

7 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 7 Object-Oriented Programming Terminology attributes: –member data of a class behaviors: –member functions of a class state: –values of an object’s variables at an instant in time

8 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 8 More on Objects data hiding: –restricting access to certain data members of an object public interface: –members of an object that are directly accessible outside of the object. –This allows the object to provide access to some data and functions without sharing its internal details and design (information hiding), and provides some protection from data corruption objects can be general-purpose or application- specific

9 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 9 Figure 12-1 Encapsulation Member Variables float width; float length; float area; Member Functions void setData(float w, float l) { … function code … } void calcArea(void) { … function code … } float getWidth(void) { … function code … } float getLength(void) { … function code … } float getArea(void) { … function code … }

10 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 10 Figure 12-2

11 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 11 General Purpose Objects –Improvements on C++’s built-in data types. For example, an array object could be created that works like a regular array, but additionally provides bounds-checking. ( vector ) –Data types that are missing from C++. For instance, an object could be designed to process currencies or dates as if they were built-in data types. –The string class provides an alternative to using C- strings. –Objects that can perform commonly needed tasks, such as input validation and screen output in a graphical user interface.

12 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 12 12.2 Introduction to Classes Objects are created from a class (instances of a class) Format: class { member data declarations member function declarations };

13 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 13 Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide( ) { return side; } };

14 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 14 Access Specifiers Used to control access to members of the class public: –can be accessed by functions outside of the class private: –can only be called by or accessed by functions that are members of the class

15 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 15 More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private

16 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 16 // This program demonstrates a simple class. #include using namespace std; // Rectangle class declaration. class Rectangle // class declaration { private: // private member data double width; double length; public: // public member functions void setWidth(double); void setLength(double); double getWidth( ); double getLength( ); double getArea( ); }; Function Prototypes private data public functions

17 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 17 Program continues // setData copies the argument w to private member // width and len to private member length. void Rectangle :: setWidth(double w) { width = w; } void Rectangle :: setLength(double l) { length = l; }

18 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 18 Program continues // getWidth returns the value in the private member width. double Rectangle::getWidth( ) { return width; } // getLength returns the value in the private member length. double Rectangle::getLength( ) { return length; } // getArea returns the value in the private member area. double Rectangle::getArea( ) { return length * width; }

19 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 19 Program continues int main( ) { Rectangle box; double rectWidth, rectLength; cout << "This program will calculate the area of a rectangle\n\n"; cout << “What is the width? "; cin >> rectWidth; cout << "What is the length? "; cin >> rectLength; box.setWidth(rectWidth); box.setLength(rectLength); cout << “\n\nHere is the rectangle's data:\n"; cout << "width: " << box.getWidth() << endl; cout << "length: " << box.getLength() << endl; cout << "area: " << box.getArea() << endl; return 0; }

20 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 20 Program Output This program will calculate the area of a rectangle. What is the width? 10 [Enter] What is the length? 5 [Enter] Here is the rectangle's data: width: 10 length: 5 area: 50

21 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 21 12.3 Defining an Instance of a Class An object is an instance of a class Defined like structure variables: Square sq1, sq2; Access public members using dot operator: sq1.setSide(5); cout << sq2.getSide(); A compiler error is generated if you attempt to access a private member using a dot operator

22 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 22 Pointer to an Object You can define a pointer to an object: Square *sqPtr; You can access public members via pointers: sqPtr = &sq1; sqPtr -> setSide(12); sqPtr = &sq2; sqPtr -> setSide(sq1.getSide()); cout getSide();

23 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 23 12.4 Why Have Private Members? Making data members private provides data protection Data can be accessed only through public functions Public functions define the class’s public interface

24 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 24 Set versus Get Functions Set function: –function that stores a value in a private member variable Get function: –function that retrieves a value from a private member variable Common class design practice: –make all member variables private, provide public set and get functions

25 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 25 12.5 Software Design Considerations –Place class declaration in a header file that serves as the class specification file. Name the file.h, for example, square.h –Place member function definitions in.cpp, for example, square.cpp File should #include the class specification file –Programs that use the class must #include the class specification file, and be compiled and linked with the member function definitions

26 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 26 13.6 Focus on Software Engineering: Some Design Considerations Usually: – class declarations are stored in their own header files. (.h ) –Member function definitions are stored in their own source files. (.cpp ) The #ifndef directive allows statements to be conditionally compiled. This prevents a header file from accidentally being included more than once.

27 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 27 Contents of rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: double width; double length; double area; public: void setData(double, double); void calcArea( ); double getWidth( ); double getLength( ); double getArea( ); }; #endif

28 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 28 Program continues Contents of rectangle.cpp #include "rectangle.h" // Rectangle Class Declaration // Rectangle Class member function definitions follow // setData copies the argument w to private member width and // l to private member length. void Rectangle::setData(double w, double l) { width = w; length = l; }...

29 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 29 Defining a Member Function When defining a member function: –Put the function prototype in the class declaration –Define the function outside of the class declaration using class name and scope resolution operator (::) int Square :: getSide() { return side; }

30 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 30 Input/Output with Objects Class should be designed to provide functions to store and retrieve data Functions that use objects of a class should perform input/output operations, not class member functions There can be exceptions to these rules: –a class can be designed to display a menu, or specifically to perform I/O

31 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 31 12.6 Using Private Member Functions A private member function can only be called by another member function It is used for internal processing by the class, not for use outside of the class A private member function is also referred to as a utility function

32 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 32 12.7 Inline Member Functions Member functions can be defined –in the class declaration ( inline ) –after the class declaration The use of the keyword inline is optional Inline member functions are appropriate for short function bodies: int getSide() { return side; }

33 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 33 Tradeoffs: Inline vs. Regular Member Functions Regular functions: –when called, compiler stores return address of call, allocates memory for local variables, etc. Inline functions: –Code for an inline function is copied into program in place of call – larger executable program, but no function call overhead, hence faster execution

34 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 34 12.8 Constructors Member function that is called when an object is created Called automatically Constructor function name is class name Has no return type ( not even void )

35 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 35 Constructor Example class Square { private: int side; public: Square(); //constructor prototype... }; Square::Square() //function header { side = 1; }

36 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 36 12.9 Destructors Member function automatically called when an object is destroyed Destructor name is ~ classname, e.g., ~Square ~ character is called the tilde Has no return type; takes no arguments Only 1 destructor per class, i.e., it cannot be overloaded If a constructor allocates dynamic memory, a destructor should release it

37 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 37 12.10 Constructors That Accept Arguments Default constructor: –constructor that takes no arguments To create an object using the default constructor, use no argument list and no () : Square square1; To create a constructor that takes arguments: –indicate parameters in prototype( if used ), definition –provide arguments when object is created: Square square2(12);

38 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 38 Constructors That Accept Arguments Constructor may have default arguments: Square(int = 1); // prototype Square::Square(int s) // heading { side = s; }

39 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 39 12.11 Input Validation Objects Objects can be designed to validate user input: –Acceptable menu choice –Test score in range of valid scores –etc. Note: input validation can be built into every class!

40 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 40 12.12 Overloading Constructors A class can have more than 1 constructor Overloaded constructors ( like any overloaded function ) in a class must have different parameter lists: Square(); Square(int);

41 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 41 Member Function Overloading Non-constructor member functions can also be overloaded: void setSide(); void setSide(int); Must have unique parameter lists as for constructors

42 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 42 12.13 Only One Default Constructor and One Destructor Do not provide more than 1 default constructor for a class: ( such as one that takes no arguments and one that has default arguments for all parameters ) Square(); Square(int = 0); // will not compile Since a destructor takes no arguments, there can only be one destructor for a class

43 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 43 12.14 Arrays of Objects Objects can be the elements of an array: Square lottaSquares[10]; The default constructor for a class is used to create the objects when the array is defined You must use an initializer list to invoke a constructor that takes arguments: Square triSqu[3] = { 5, 7, 11 }; More complex initialization is required if the constructor takes more than 1 argument ( constructor function notation ).

44 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 44 Accessing Objects in an Array Objects in an array are referenced using subscripts Member functions are referenced using dot notation: lottaSquares[3].setSide(6); cout << triSqu[i].getSide();

45 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 45 12.17 is optional

46 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 46 12.17 An Object-Oriented System Development Primer Procedural Programming: –program is made up of procedures: sets of programming statements that perform tasks Object-Oriented Programming: –program is made up of objects: entities that contain data (attributes) and actions (behaviors)

47 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 47 Benefits of Object-Oriented Programming Simplification of software development for graphical (GUI) applications –visual components (menus, text boxes, etc.) modeled as objects –visual components (e.g., windows) may be made up of multiple objects –some objects (e.g., buttons) may have member functions associated with them

48 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 48 Benefits of Object-Oriented Programming Simplification of software development for non-GUI applications - the problem: –procedural programming enforces separation between code and data –changes in data format require extensive analysis, testing to ensure program functionality

49 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 49 Benefits of Object-Oriented Programming Simplification of software development for non-GUI applications - a solution: –OO programming addresses the problem through encapsulation: combination of data (attributes) and actions (behaviors) in an object data hiding: protection of an object’s data by making it private and providing a public interface

50 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 50 Component Reusability Component: –a software object that performs a well-defined task or that provides a service Component Reusability: –the ability to use a component in multiple programs without (or with little) modification

51 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 51 Relationships Between Objects A program may contain objects of other classes ( composition ) Objects may be related by one of the following: –Access ( ‘uses a’ relationship) –Ownership ( ‘has a’ relationship) –Inheritance( ‘is a’ relationship)

52 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 52 Messages and Polymorphism Message: –request to an object to perform a task. Implemented as a member function call Polymorphism: –ability to take many forms. Sending the same message to different objects may produce different behaviors ( objects have a commonly named method )

53 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 53 Object Oriented Analysis Used to create the logical design of a system, what the system is to do Usually includes –examine the problem domain; model the system from within that perspective –identify the objects that exist within the boundaries of that system –identify the relationships between the objects –realize that there may be many ‘right’ solutions

54 4 th Ed. Home Page4 th Ed. Home Page Appendices AppendicesChapter 12 slide 54 Object Oriented Design Used to determine how requirements from OO Analysis will be implemented Usually includes: –determine hierarchical relationship between objects –determine object ownership of attributes –implement and test; refine as required


Download ppt "Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 12 Introduction to Classes."

Similar presentations


Ads by Google