1 / 52

CIS162AB - C++

CIS162AB - C++. Structures and Classes Juan Marquez 10_classes.ppt. Overview of Topics. Procedural Programming Object-Oriented Programming (OOP) Structures Class vs Object Unified Modeling Language (UML) Defining Classes Using Classes Constructors and Destructors.

marla
Download Presentation

CIS162AB - C++

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. CIS162AB - C++ Structures and Classes Juan Marquez 10_classes.ppt

  2. Overview of Topics • Procedural Programming • Object-Oriented Programming (OOP) • Structures • Class vs Object • Unified Modeling Language (UML) • Defining Classes • Using Classes • Constructors and Destructors

  3. To this point we have been doing procedural programming using modular and structured techniques. The emphasis is on the procedures that make up the solution. Choose data type (int, double, etc). Define operations, procedures, and processing of data. Design algorithm (flowcharts & pseudocode). Translate algorithm into code. Data is considered separate from procedures. Data declarations and procedures duplicated throughout various programs. Procedural Programming Characteristics

  4. Procedural Programming Process • Program 1: • Declare variables: double rate; • Define functions: double inputRate( ); • Program 2: • Declare variables: double rate; • Define functions: double inputRate( ); • Function in Library: • Declare variables in program: double rate; • Include function definition. • Procedures still separate from data.

  5. Object-Oriented Programming • The emphasis is on the objects that make up the solution. • Combines the power of procedural programming with added dimensions. • Must still choose data types (int, double, etc). • Define operations on data. • Input from keyboard. • Including data validation. • Design algorithm for operations. • Translate algorithm to code. • Combine data and pertinent operations together into a class definition.

  6. Class and Objects • A class is a definition of a new data type. • A class definition includes members variables as well as associated functions. • An object is a variable declared using a class definition as the data type. • A class is the definition, and an object is an instanceof the class.

  7. Class Analogy • A class is like a blueprint of a house. • Each house being built allows for the selection of tile, carpet, and wall colors. • So on the order form their may be a blank line to enter the color chosen, much like a variable. • Each house built based on the blueprint is an instance of the house.

  8. Object Analogy • The house is the object. • The object has specific values, such as the colors chosen by the homeowner, but the class allows for color selection. • The homebuilder may offer various methods of applying the paint, such as roller, brush, or sponge. • If they don’t apply the paint, what’s the point in choosing colors. • Many houses may be built from the same blueprint. • Most will have different colors • Some may have the same colors, but they will still be distinct instances of the blueprints. • Two families wouldn’t move into the same house just because they chose the same colors .

  9. OOP Process • OO Programming involves using existing classes (ifstream, string), and sometimes we define new classes. • Define class (PayRateClass) • Define variables: double rate; • Define operations: inputRate();setRate( ); getRate(); • Program 1: • Declare an object of the type PayRateClass • Program 2: • Declare an object of the type PayRateClass • Both include the data and operations.

  10. Student Information System • Consider what date fields are recorded in a Student Information System. • Birth Date • Enrollment Date • Payment Date • Withdrawal Date • Completion Date • Course Start Date • Course End Date • Graduation Date • Many more…

  11. Date Collection • How are the dates collected? • Screen or form to collect each one. • Most have the same edits. • A lot of duplicate code and maintenance. • Data is collected and saved to a file. • Data is then retrieved and used : • In update screens • In reports • As selection criteria for reports • It might make sense to create a class to handle the collection, validation, and processing of dates.

  12. Structures • In C there is only structures. • In C++ there are structures and classes. • A structure is a definition of a new data type or data structure. • A structure includes member variables, but does NOT include the associated functions. • 2 steps - • Define structure. • Use structure in a program. • 1St we’ll look at structures, and then classes.

  13. Date Structure Defined struct dateMDY //structure tag{ int month; //member types and names int day; int year;};//semi-colonrequired because variables of this structure type can be declared right after the closing brace. For example:} bday, payday;

  14. Date Variable Declared int hours; //data type - variabledateMDY bday; //Structure - variablebday.month = 10; //individual members are variables.bday.day = 31; //individual members referenced bday.year = 1970; //using variable name and a dot. dateMDY payday; //many variables of the structure //type can be created.payday.month = 4;payday.day = 7; //each instance has its own payday.year = 1999; //memory allocation.

  15. Structures as a Group //declare structure variabledateMDY salesDate, dueDate;dueDate.month = salesDate.month; //use individual dueDate.day = salesDate.day; //members as dueDate.year = salesDate.year; //regular variables //OR – equate as a groupdueDate = salesDate; //individual members copied //An entire structure can be passed to functions using the structure type as a parameter type.displayDate(dateMDY date);

  16. Structures and Classes • Structures only contain variables. • The operations on the data are separate. • Structures are very similar to classes. • Classes have member variables, and in addition, they have associated member functions. • Having functions allows us to encapsulate the operations on the data with the variables. • C++ support classes, while C doesn’t. • So C++ is consider an Object Oriented Programming language.

  17. Class Outline • Class Name • Properties (variables) • Properties are used to record the current state of an object. • The values in the variables represent the current state. • Operations (functions) • Operations are used to modify the values of the members variables.

  18. Date Class Designed • Back to the supporting the date in a Student Information System. • Instead of a structure, we can create a class to handled the dates that may support: • Data validation for the month, day, year. • Date displayed in different formats. • Class designs can be represented using Unified Modeling Language (UML). • Class Notation

  19. Class Notation • 3 sections in the drawing • Class Name • Properties (variables) • Operations (functions) • Properties and operations can be either • public, private, or protected • protected –same as private but used in inheritance • The variables and functions are considered members.

  20. UML – Class Notation • Notation: - private + public # protected

  21. Date Class Notation • Notation: • - private • + public • # protected

  22. DateMDY Definition //convention - class names begin with a capital letter. class DateMDY //class tag { public: int month; //member variables int day; int year; void displayDate( ); //member prototypes }; //Note that there isn’t a main function in this class. //This class cannot be executed. //It is merely a definition for other programs to use. //There isn’t any code here for displayDate, however //there are provisions to do that (inline functions).

  23. Declaring an Object • An object is a variable declared using a class as the data type. • Declaring a primitive variable.dataType variable;double price; • Declaring an object.ClassName object;DateMDY bday;

  24. Instantiation • The process of creating an object of a class. DateMDY bday; • It’s call a process because • Memory is allocated, and • A constructor function is called. • Constructor functions are introduced a few slides later…

  25. Referencing Object Members • After declaring an object use dot operator between object name and members.objectName.variable and/or objectName.function( )bday.month bday.displayDate( )bday.daybday.year • We can have many variables and functions included in a class definition.

  26. Prior Class Examples • The string data type is a class. string firstName; firstName.length() firstName.empty() • The ifstream data type is a class. ifstream inFile; inFile.open("p09ex.txt");

  27. Using DateMDY Class void main ( ) { // istream infile; //className object; DateMDY bday; bday.month = 11; bday.day = 30; bday.year = 1981; bday.displayDate( ); }

  28. Class and Function Definitions class DateMDY { public: int month; //member variables int day; int year; void displayDate( ); //member prototypes }; //after main void DateMDY::displayDate( ) //:: scope resolution { cout << month << “/” << day << “/” << year; }// Do NOT use the class name and dot operator in the body of the function definition.

  29. Multiple Objects • You can create many instances/objects of a class in the same program. • Each object will have their own memory allocation.DateMDY bday;DateMDY dueDate; • Member variables are also known as instance variables. • They are not shared among objects.

  30. Public vs Private Members • Public variables can be referenced and altered by functions outside of the class (main) (month, day, year). • Public functions can be called by functions outside of the class (displayDate). • Private variables can only be referenced and altered by member functions. • Private functions can only be called by member functions. • Private is the default if not specified. • Protected – applies to inheritance. • Is basically the same as private. • Can be accessed by class members and subclass members only.

  31. Class Abstraction • Classes are defined for other programmers to use or for you to use in many programs. • A class is created because we want a data type that is self contained. • Users of a class should only be concerned with what the class does and not how it does it. • If used correctly, the class should function as expected every time. • So we don’t want other programmers changing important values or calling functions that change values in member variables.

  32. Accessor Functions • To keep programmers from referencing variables that they shouldn’t we can make them private members. • We must then provide accessor functions that allow programmers to set and get the values stored in the private variables.

  33. Improved DateMDY Class • Notation: • - private • + public • # protected

  34. Improved DateMDY Definition class DateMDY { private:int month, day, year; public: void setMonth(int m); int getMonth( ); void setDay(int d); int getDay( ); void setYear(int y); int getYear( ); void displayDate( ) } ;

  35. void DateMDY::setMonth(int m){ month = m;} int DateMDY:: getMonth( ) { return month;} void DateMDY::setDay(int d){ day = d;} int DateMDY:: getDay( ) { return day;} void DateMDY::setYear(int y){ year= y;} int DateMDY:: getYear( ) { return year;} Accessor Function Definitions

  36. Using Accessors void main( ) //driver to test class DateMDY {DateMDY bday; bday.setMonth(11);bday.setDay(30); bday.setYear(1970);bday.displayDate( );int year;year = bday.getYear( ): cout << year;//year = bday.year //invalid because year in class is private }

  37. Complete Support of Class • Since the variables are private, only member functions can change or get the values. • So the class should have functions that allow the manipulation of the data. • What if we want to know what the date will be 30, 60, or 90 days from now? • What if we want to know the date 30, 60, or 90 days ago? • We need functions that allows us to do this (ie):addDays(int numberOfDays)subtractDays(int numberOfDays)

  38. Date Considerations • Increase days first, then month, then year. • Leap year? • Display date in various formats: • MM/DD/YYYY • Month DD, YYYY • Etc. • Before taking this example too far, you should know that C++ includes a Date class…(CTime defined in time.h)

  39. Friend Functions • A friend function is not a member function of the class, but it has the same privileges as a member. • This grants them access to the private members. • Use sparingly. • Usually used to overload operators. • Overload covered in next chapter. DateMDY addDays(int numberOfDays); friend operator +(DateMDY& date, int numberOfDays);//this is called operator overloading.

  40. Passing Objects to Functions • Individual public variables can be passed to functions. • Entire objects can be passed to functions:void add30Days(DateMDY& dueDate); • This is a void because the object is a call-by-reference parameter instead of a call-by-value. • The reference (address) is passed to the function, so the local object actually points to the location of the original object. • Any changes performed in the function will effect the original object. • In a call-by-value the changes will be local to the function.

  41. Constructor Characteristics • A special functionof the class. • Same name as the class. • Can NOT return a value. • Has no return type, not even void. • Primarily used to initialize member variables. • Automatically called when an object of that class type is declared.

  42. Default Constructor • Default constructor has no parameters. • Always define a default constructor. • If one is not defined,the compiler will generate one.class DateMDY{public: DateMDY( );…

  43. Overloaded Constructors • Constructors can be overloaded. • Same function name but a different number or type of parameters. • Initial values can be passed at declaration if there is a constructor with parameters.DateMDY(int m, int d, int y);

  44. Constructor Prototypes class DateMDY { public: int month; int day; int year; DateMDY( ); //default constructor DateMDY(int m, int d, int y); //overloaded void displayDate( ); } ;

  45. Constructor Definitions DateMDY::DateMDY( ) //do nothing or set default values { month = 0; day = 0; year = 0; } DateMDY::DateMDY(int m, int d, int y) //overloaded { month = m; day = d; year = y; } void DateMDY::displayDate() { cout << month << “/” << day << “/” << year; }

  46. Using Constructors • For each object below, determine which constructor is called and what would be dispalyed. void main( ) { DateMDY bday; bday.displayDate(); DateMDY payday (2, 26, 2002); payday.displayDate(); }

  47. Constructor Examples string name; //defaultstring name (“Marquez”); //overloaded istream inFile; //defaultistream inFile (“infile.txt”); //overloaded

  48. Explicit Constructor Calls • Constructors are automatically called when an object of that class type is declared. • Constructors can also be called explicitly after an object has been declared. • Syntax: bday = DateMDY( );//not bday.DateMDY( ); • Can be used to reset values in member variables if object was part of a loop.

  49. Destructor • A member function that is automatically called when object goes out of scope. • Must be public. • Same name as the class, but begins with ~ tilde. • Can NOT return a value. • Has no return type, not even void. • Can be used to “cleanup” dynamic variables. ~DateMDY( );

  50. Destructor Prototypes class DateMDY { public: int month; int day; int year; DateMDY( ); //default constructor DateMDY(int m, int d, int y); //overloaded~DateMDY( ); //destructor void displayDate( ); } ;

More Related