660 likes | 800 Views
10. Introduction to Classes. Contents. Abstract data types in C++ (Classes) Constructors A case study involving constructing a room object Object identification and the Unified Modeling Language (UML) Common programming errors. Abstract Data Types in C++ (Classes).
E N D
10 Introduction to Classes
Contents • Abstract data types in C++ (Classes) • Constructors • A case study involving constructing a room object • Object identification and the Unified Modeling Language (UML) • Common programming errors
Abstract Data Types in C++ (Classes) • Procedural, hybrid, and pure object-oriented languages • Pure object-oriented language: Smalltalk, Eiffel • C++ is an object-oriented hybrid language. • An object oriented approach fits graphically windowed environments • Abstract data types: Central to creation of objects; a user defined data type rather than a built-in data type
Abstract Data Types • Data type: Combination of data and associated operations • A data type defines both the types of data and the types of operations that can be performed on the data • Data type = Allowable Data Values + Operational Capabilities
Abstract Data Types • Abstract data type (ADT): User defined type that specifies both a type of data and the operations that can be performed on it • User defined types are required when you want to create objects that are more complex than simple integers and characters • Data structure: How data is stored • Class: C++ name for an abstract data type
Class Construction • Two components: • Declaration section: Declares data types and function for class • Implementation section: Defines functions whose prototypes were declared in declaration section • Class members: • Data members (instance variables) • Member functions
Class Construction // class declaration section class classname { data members // the variables function members // prototypes }; // class implementation section function definitions
Class Construction • Example of class declaration section: class Date { private: int month; int day; intyear; public: Date(int = 7, int = 4, int = 2006); void setDate(int, int, int); void showDate(void); }; // this is a declaration – // don't forget the semicolon
Class Construction • Declaration section of class definition • Enclosed in braces • Includes variables (data members) and function declarations • Keywords private and public: Define access rights • private: Class members (month, day, and year) can only be accessed using class functions • Enforces data security (data hiding) • public: class members (functions Date(), setDate(), showDate() can be used outside of the class
Class Construction • Constructor function: Initializes class data members with values • Constructor function (Date()) has same name as the class • Default values for constructor are 7, 4, 2006 • Constructor function has no return type (a requirement for this special function) • Two remaining member functions: setDate() and showDate() declared as returning no value (void)
Class Construction • Implementation section of class definition • Functions: Defined same as other C++ functions but also includes scope resolution operator • To identify function as member of class • Implementation and declaration sections declare a class • Variables of the class (objects) must still be defined
Class Construction Example: Creation of objects of Date class in main() function of Program 10.1 int main() { Date a, b, c(4,1,2000); // declare 3 objects b.setDate(12,25,2006); // assign values to b's // data members cout << endl; a.showDate(); // display object a's values b.showDate(); // display object b's values c.showDate(); // display object c's values cout << endl; return 0; }
Class Construction • Description of main(): • Three objects of class Date defined • Constructorfunction: Date(), automatically called • Memory allocated for each object • Data members of the objects initialized • Object a: No parameters assigned therefore defaults are used: a.month = 7 a.day = 4 a.year = 2005
Class Construction • Description of main(): (continued) • Notation to create objects: objectName.attributeName • Object b: No parameters assigned, same defaults used • Object c: Defined with arguments 4, 1, and 1998 • Three arguments passed into constructor function resulting in initialization of c’s data members as: c.month = 4 c.day = 1 c.year = 2000
Class Construction • Description of main(): continued • All function of class Date are public, therefore • b.setDate(12, 25, 2006)is a valid statement inside main() function • Calls setDate() function with arguments 12 ,25, 2006 • Important distinction: Data members of class Date are private • The statement b.month = 12 is invalid in main()
Class Construction • Description of main(): continued • Last three statements in main() call showDate() to operate on a, b, and c objects • Calls result in output displayed by Program 10.1 The date is 07/04/06 The date is 12/25/07 Thedate is 04/01/98 • The statement cout << a; is invalid within main() • cout does not know how to handle an object of class Date
Class Construction • Program 10.1 • #include <iostream> • #include <iomanip> • using namespace std; • // class declaration • class Date • { • private: • int month; • int day; • int year; • public: • Date(int = 7, int = 4, int = 2005); // constructor • void setDate(int, int, int); // member function to copy a date • void showDate(); // member function to display a date • };
Class Construction • Program 10.1 (Continued) • // implementation section • Date::Date(int mm, intdd, intyyyy) • { • month = mm; • day = dd; • year = yyyy; • } • void Date::setDate(int mm, intdd, intyyyy) • { • month = mm; • day = dd; • year = yyyy; • return; • }
Class Construction • Program 10.1 (Continued) • void Date::showDate() • { • cout << "The date is "; • cout << setfill('0') • << setw(2) << month << '/' • << setw(2) << day << '/' • << setw(2) << year % 100; // extract last 2 year digits • cout << endl; • return; • }
Class Construction • Program 10.1 (Continued) • int main() • { • Date a, b, c(4,1,2000); // declare 3 objects • b.setDate(12,25,2006); // assign values to b's data members • a.showDate(); // display object a's values • b.showDate(); // display object b's values • c.showDate(); // display object c's values • cout << endl; • return 0; • }
Terminology • Class: Programmer-defined data type • Objects (instances): Created from classes • Relation of objects to classes similar to relation of variables to C++ built-in data types • int a; // a is a variable of type integer • Date a; // a is an object of class Date • Instantiation: Process of creating a new object • Creates new set of data members belonging to new object: Determines the object’s state
Terminology • Interface: Part of class declaration section • Includes: • Class’s public member function declarations • Supporting comments • Implementation: Consists of: • Implementation section of class definition • Private member functions • Public member functions • Private data members from class declaration section
Terminology • Information hiding: • Internal construction of class is not relevant to programmer who just wishes to use class • Implementation can and should be hidden from all users • Ensures that class is not altered or compromised in any way • Information needed by programmer to use class is provided by interface
Constructors • A function that has same name as its class • Multiple constructors can be defined for a class • Each must be distinguishable by the number and types of its parameters • This is an example of function overloading • If no constructor function is written, compiler assigns default constructor • Purpose: Initialize a new object’s data members • May perform other tasks
Constructors • Format: Same name as class to which it belongs • Must have no return type (not even void) • Default constructor: Does not require arguments when called • Two cases: • No parameters declared • As with compiler-supplied default constructor • Arguments have already been given default values in valid prototype statement: • Date (int = 7, int = 4, int = 2005) • Declaration Date a; initializes the a object with default values: 7, 4, 2006
Constructors • Sample class declaration: class Date { private: int month, day, year; public: void setDate(int, int, int); void showDate() };
Constructors • No constructor has been included • Compiler assigns a do-nothing default constructor equivalent to: Date (void) { } • This constructor expects no parameters, and has an empty body
Constructors Constructor Format • classname::classname(parameter list) • { • // function body • }
Constructors Use of constructor in main() - Program 10.2 • int main() • { • Date a; // declare an object • Date b; // declare an object • Date c (4,1,2006); // declare an object • return 0; • }
Constructors • Program 10.2 • #include <iostream> • using namespace std; • // class declaration section • class Date • { • private: • int month; • int day; • int year; • public: • Date(int = 7, int = 4, int = 2005); // constructor • };
Constructors • Program 10.2 (Continued) // implementation section • Date::Date(int mm, intdd, intyyyyy) • { • month = mm; • day = dd; • year = yyyyy; • cout << "Created a new data object with data values " • << month << ", " << day << ", " << year << endl; • } • int main() • { • Date a; // declare an ojbect • Date b; // declare an object • Date c(4,1,2006); // declare an object • return 0; • }
Constructors Output from Program 10.2 Created a new data object with data values 7, 4, 2005 Created a new data object with data values 7, 4, 2005 Created a new data object with data values 4, 1, 2006
Calling Constructors • Constructors are called when an object is created • Declaration can be made in a variety of ways • Date c(4,1,2006); • Date c = Date(4,1,2006); • Date c = 8; • An object should never be declared with empty parentheses • Date a(); • Not the same as the declaration Date a; • Does not result in an object being created
Overloaded and Inline Constructors • Primary difference between a constructor and other user-written functions is how the constructor is called • Constructors are called automatically each time an object is created • Most other functions must be called explicitly by name • Inline functions are functions defined in the class declaration section
Destructors • Destructor functions: Counterpart to the constructor functions • Destructors: • Are functions with the same name as constructors but are preceded with a tilde (~) • For the Date class the destructor name is ~Date() • Take no parameters and return no values • There can only be one destructor per class
Destructors • Destructors: • Called automatically when an object goes out of existence • Clean up any undesirable effects the object might leave, such as releasing memory stored in a pointer
A Case Study: Constructing a Room Object • Applying your knowledge of classes: Create a class from which room objects can be created • Room’s floor area must be calculated for any size room when its length and width are known • For modeling purposes, assume every room is rectangular
A Case Study: Constructing a Room Object • Coding the solution class RoomType { // data declaration section private: double length; // declare length as a double variable double width; // declare width as a double variable public: RoomType(double = 0.0, double = 0.0); // the constructor's declaration // statement void showRoomValues(); void setNewRoomValues(double, double); void calculateRoomArea(); };
A Case Study: Constructing a Room Object RoomType::RoomType(double l, double w) // this is a constructor { length = l; width = w; cout << "Created a new room object using the default constructor.\n\n"; } void RoomType::showRoomValues() // this is an accessor { cout << " length = " << length << "\n width = " << width << endl; } void RoomType::setNewRoomValues(double l, double w) // this is a mutator { length = l; width = w; } void RoomType::calculateRoomArea() // this performs a calculation { cout << (length * width); }
A Closer Look: Object Identification and the Unified Modeling Language (UML) • When solving any problem, it is often helpful to start by creating a diagram or map or devising a theoretical analogy for the problem you are trying to solve • The first step in constructing an object-based program is developing an object-based model of the program
A Closer Look: Object Identification and the Unified Modeling Language (UML) Figure 10.1 A class is a programming-language description of a model
Representing Problems with Models • A model is a representation of a problem • First step in creating an object-based model is to begin “thinking in objects” • Objects can be modeled by two basic characteristics • Attributes define the properties of interest • Behaviors define how the object reacts to its environment
Representing Problems with Models • Two steps to designing and developing an object-oriented program • Identify the required objects • For each object • Identify the attributes of interest • Indentify the behaviors (operations) of interest • Object description diagram: Summarizes initial results of the two steps in a form that can be translated into a programming language
Representing Problems with Models Figure 10.2 An initial object diagram
Representing Problems with Models • Unified Modeling Language (UML) is a widely accepted technique for developing object oriented programs • A program-modeling language • Uses diagrams and techniques that are easy to understand and support all the features required to implement an object-oriented design
Representing Problems with Models • Designing an object-oriented program requires understanding and specifying • The objects in the system • What can happen to these objects • When something can happen to these objects
Representing Problems with Models • UML provides seven diagram types • Class • Object • State • Sequence • Activity • Use case • Component • Deployment
Class and Object Diagrams • Class diagrams are used to describe classes and their relationships • Object diagrams are used to describe objects and their relationships • Both classes and objects are represented with a diagram consisting of a box • In class diagrams, the class name is in bold text and centered at the top of the box • In object diagrams, the object’s name is also centered at the top of the box, underlined
Class and Object Diagrams Figure 10.3 Class and object representations
Class and Object Diagrams Figure 10.5 Including attributes in UML class and object diagrams