1 / 32

Chapter 6: Classes

Chapter 6: Classes. Chapter Goals To be able to implement your own classes To master the separation of interface and implementation To understand the concept of encapsulation To design and implement accessor and mutator member functions To understand object construction

nixie
Download Presentation

Chapter 6: Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6: Classes • Chapter Goals • To be able to implement your own classes • To master the separation of interface and implementation • To understand the concept of encapsulation • To design and implement accessor and mutator member functions • To understand object construction • To learn how to distribute a program over multiple source files

  2. Discovering Classes (1) • If you find yourself defining a number of related variables that all refer to the same concept, define a class that abstracts the concept and contains these variables as data fields. • Example: • Suppose you are reading information about computers: • Model Name • Price • Score between 0 and 100 • Sample data: • ACMA P600, 995, 77 • Alaris Nx868, 798, 57

  3. Discovering Classes (2) • Sample code excerpt: if (next_score / next_price > best_score / best_price) { best_name = next_name; best_score = next_score; best_price = next_price; } • Each of these sets of variables describes a product (a best product, and the next product read in). We need to develop a Product class.

  4. Discovering Classes (bestval.cpp)-1 #include <iostream>#include <string>usingnamespace std; int main() {      string best_name = "";    double best_price = 0;    int best_score = 0;    bool more = true;while (more) {         string next_name;       double next_price;       int next_score;       cout << "Please enter the model name: ";getline(cin, next_name);       cout << "Please enter the price: ";       cin >> next_price;       cout << "Please enter the score: ";       cin >> next_score;       string remainder; /* read remainder of line */getline(cin, remainder);

  5. Discovering Classes (bestval.cpp)-2 if (next_score / next_price > best_score / best_price){       best_name = next_name;     best_score = next_score;     best_price = next_price; }     cout << "More data? (y/n) "; string answer;getline(cin, answer);if (answer != "y") more = false; } cout << "The best value is " << best_name      << " (Score: " << best_score      << " Price: " << best_price << ")\n";return 0; }

  6. Interface • To define a class, we first need to specify an interface. • The interface consists of all member functions we want to apply to objects of that type. • The interface is specified in the class definition. • Example: Product class member functions: • Make a new product. • Read in a product object. • Compare two products and find out which one is better. • Print a product.

  7. Interface (cont.) • Product class header class Product{public:  Product();  void read();  bool is_better_than(Product b) const;  void print() const;private:  … implementation details};

  8. Interface (Syntax 6.1 : Class Definition) • General syntax class Class_name { public: -constructor declarations -member function (operations) declarations private: -data fields -private functions }; • Purpose:Define the interface and data fields of a class.

  9. Interface (Syntax 6.1 : Class Definition) • Example: class Point { public: Point (double xval, double yval); void move(double dx, double dy); double get_x() const; double get_y() const; private: double x; double y; };

  10. Class Interface (cont.) • The class interface is usually placed in “.h” (header) file. • The name of the file is “<class_name>.h” • The interface must be included inside: #ifndef … #endif preprocessor statements • This defines a macro that avoids multiple declarations of same elements

  11. Class Interface (cont.) • Example of header file for previous class: // File: Point.h #ifndef __POINT_H__ #define __POINT_H__ class Point { public: Point (double xval, double yval); void move(double dx, double dy); double get_x() const; double get_y() const; private: double x; double y; }; #endif • Final implementation will be in file: “Point.cpp” …

  12. Interface • The first member function is a constructor: the function that is used to initialize new objects. • This constructor has no parameters so it is called a default constructor. • Default constructors are automatically used when you construct an object without parameters. Example: Product best; /* default construction */ • Every class should have a default constructor, and there might be other constructors. • The read() member function is a mutator function - an operation that modifies the object. • The last two member functions are accessor functions - functions that query the object for some information without changing it. • The keyword const indicates that the implicit parameter object is not modified by the member function.

  13. Encapsulation • Classes are broken into public and private sections. • The data items (attribute fields) are defined in the private sections of the class definition. • Example: class Product { public: Product(); void read(); bool is_better_than(Product b) const; void print() const; private: string name; double price; int score; };

  14. Encapsulation (cont.) • Only constructors and member functions can access private data. • Hiding data is called encapsulation. • Encapsulation forces indirect access to the data, guaranteeing that it cannot accidentally be put in an incorrect state. • The unique access is through member functions • Goal is to avoid uncontrolled modifications to data object.

  15. Member Functions • Each member function advertised (prototype is given without implementation) in the class interface must be implemented separately. • A Class_name:: prefix makes it clear that we are defining a member function for that class. • The operator :: is name resolution operator. • Example: Product::Product() { … function body … } void Product::read() { … function body … }

  16. Member Functions (cont.) • A member function is called object.function_name(…) • The object to which is applied is the implicit object. • Any data field used in a member function corresponds then to the particular data field in the implicit object. • Example: Product next, other; // automatically applies default // constructor to initialize // objects next and other ……. next.read(); // applies method read() to next other.read() // applies method read() to other

  17. Const Member Functions • When the keyword const is used in the declaration, it must also be placed in the member function definition. Example: void Product::print() const { cout << name << " Price: " << price << " Score: " << score << "\n"; } • The keyword const indicates that the member function will not modify the object that called it.

  18. Example for Project 1 This example shows one possible way to specify the class to manage the rectangles that need to be drawn as part of Project 1. But be aware that there are better options… //File: Rectangle.h #ifndef __RECTANGLE_H__ #define __RECTANGLE_H__ #include “Point.h” using namespace std; class Rectangle { public: void setTo(const Point& ulc, const Point lrc); void setToFillBlack(); void draw() const; private: Point ul, lr; // upper left & lower right corners bool isDark; // true => fill black when drawing void fillBlack(); //to fill when drawing, if needed }; #endif

  19. Member Functions (Rectangle) • Let’s implement some of the member functions: (comments are missing) // File: Rectangle.cpp #include “Rectangle.h” … other includes … void Rectangle::setTo(const Point& ulc, const Point lrc) { ul = ulc; // upper left corner lr = lrc; // lower right corner isDark = false; // default is DO NOT FILL } void Rectangle::setToFillBlack() { fillBlack = true; } …. Other stuff ….

  20. Default Constructors • The purpose of a constructor is to initialize all data fields of an object. • A constructor always has the same name as the class. • A default constructor has no parameters. Example: Product::Product() { price = 0; score = 0; } This example says that a variable declared of type Product, as in the declaration: Product t, w; will automatically have its internal fields initialized to 0. • Most default constructors initialize the data fields to some standard value (e.g. 0 for numeric, NULL for pointer, etc) • The Time class initializes to current time. • The string class initializes to empty string.

  21. Default Constructors (cont.) If not explicitly included • compiles generates one default constructor. • to reserve the minimum memory space to be assigned to the object being declared. • particular fields are not initialized unless they are assigned default values because of their particular types. • For example, if a particular field is of type Time, then it will have default initial value.

  22. Constructors with Parameters • Constructors with Parameters • It's possible to create a class with more than one constructor. Example: Employee Fred; // uses default constructor Employee Harry("Harry Hacker", 40000); // uses alternate constructor • All constructors have the same name as the class, but have different parameter lists.

  23. Example with Several Constructors class Employee {  public: Employee() Employee(string employee_name, double initial_salary); void set_salary(double new_salary); string get_name() const; double get_salary() const; private: string name; double salary; };

  24. Constructors with Parameters (cont.) • Whenever two functions have the same name but are distinguished by their parameter types, the function name is overloaded. • The second constructor (in class Employee) sets the data fields of the new object based on the parameters. Employee::Employee(string employee_name, double initial_salary) { name = employee_name; salary = initial_salary; } • Example of declaration: Employee e1(“maria”, 45000);

  25. Constructors with Parameters (cont.) • Sometimes a constructor gets more complex because one of the data fields is itself an object of another class with its own constructor. • Example: suppose we modify the Employee class so that each Employee has scheduled work hours. class Employee { public: Employee(string employee_name, double initial_salary, int arrive_hour, int leave_hour);    . . . private: string name; double salary; Time arrive; Time leave; };

  26. Constructors with Parameters (cont.) • The constructor must initialize the time fields using the Time() constructor. Employee::Employee(string employee_name, double initial_salary,    int arrive_hour, int leave_hour) { name = employee_name;  salary = initial_salary;    arrive = Time(arrive_hour, 0, 0);    leave = Time(leave_hour, 0, 0);}

  27. Constructors with Field Initializer List • Syntax: Class_name::Class_name(parameters): field1(expr),…, fieldn(expr){ … statements … } • Example: Point::Point(double xval, double yval): x(xval), y(yval) { … body statements … } • Purpose: Supply the implementation of a constructor, initializing data fields before the body of the constructor. • The syntax above is an alternate, and more efficient, way to initialize data field, but many programmers find it confusing. • This syntax is necessary to construct objects of classes that don't have a default constructor.

  28. Accessing Data Fields • Only member functions of a class are allowed to access the private data fields of objects of that class. void raise_salary(Employee& e, double percent) { e.salary = e.salary * (1 + percent / 100 ); /* Error */ } • Data fields must be accessed by accessor and mutator functions. void raise_salary(Emplyee & e, double percent) { double new_salary = e.get_salary() * (1 + percent / 100); e.set_salary(new_salary); }

  29. Accessing Data Fields (cont.) • Not every data member needs accessor functions (the Product class did not have a get_score() function). • Not every get_ function needs a matching set_ (the Time class can get_minutes() but not set_minutes() ). • Remember that implementation is supposed to be hidden - just because a class has member functions named get_ or set_ does not necessarily explain how the class is designed.

  30. Member vs. Nonmember Functions • Consider the nonmember function void raise_salary(Employee& e, double percent) { double new_salary = e.get_salary() * (1 + percent / 100); e.set_salary(new_salary); } versus the member function void Employee::raise_salary(double percent) { salary = salary * (1 + percent / 100); }

  31. Member vs. Nonmember Functions • The previous nonmember function is called with two explicit parameters. Example: raise_salary(harry, 7); • A member function is called using the dot notation, with one explicit parameter and one implicit parameter. Example: harry.raise_salary(7); • A member function can invoke another member function on the implicit parameter without using the dot notation. Example: void Employee::print() const { cout << "Name: " << get_name() << "Salary: " << get_salary() << "\n"; }

  32. 7 UPR- RUM INEL 5 ICOM Aniversario El Departamento de Ingeniería Eléctrica y Computadoras te invita a su Cena Gala Pro-Edificio INEL-ICOM Amenizan: Michael Stuart Grupo Somos Seis Sábado, 4 de octubre de 2003,6:30 pm Coliseo Rafael A. Mangual Recinto Universitario de Mayaguez Para información llame: (787) 265-3821 http://alumni.ece.uprm.edu Donativo: $50 por persona $30 por estudiante Michael Stuart 75 años de historia… diseñando el futuro. AuspiciaN Bronce Oro Plata

More Related