III. Classes (Chap. 3)
|
|
- Blaise Haynes
- 5 years ago
- Views:
Transcription
1 III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char, bool, complex, and the related types (unsigned, short, etc.) enumerations Structured: These store collections of data. arrays, structs, unions, classes, valarrays, bitsets, and the containers and adapters in STL We have studied all of the fundamental types (except complex) and the data structures C++ gets from C arrays, structs, and unions. We will now look at classes in detail; pointers (and linked structures that use pointers) and vectors, stacks, queues, and lists from STL will be considered soon. A. Structs vs. Classes Similarities between structs and classes 1. Both can be used to model objects with (also called fields or instance variables). They can thus be used to process 2. They have essentially the. Differences between structs and classes 1. C does not provide classes; C++ provides both structs and classes. 2. Members of a struct by default are (can be accessed ). In C++ they can be explicitly declared to be (cannot be accessed outside the struct). Members of a class by default are Thus, choosing which to use is not based on their capabilites. It is common practice to use classes to prevent users of a new data type from (directly) accessing the data members. (We can also enforce this with structs, but this is not their default nature.) Differences between "traditional" (C) structs and OOP (C++) structs and classes C++'s structs and classes are extensions of C's structs. They can be used to model objects that have: Attributes (characteristics) represented as data members and
2 III-2 III. Classes Terminology: It is common to call the two parts of a class data members and member functions (although "data members" and "function members" is really more correct.) We will use the terms interchangeably. This is an important difference because it leads to a whole new style of programming object-oriented rather than procedural. Objects can now be, carrying their own operations around with them commonly called the principle instead of having to be shipped off to some external function that operates on them and sends them back. B. Structure and Design of a Class ( 11.1) 1. Declaring a Class a. Usual Form: class ClassName public: Declarations of public members private: Declarations of private members ; Notes: 1. The data members are normally placed in the section of a class; the function members in the section. 2. Some programmers prefer to put the private section first because this is the default access for classes so the private: specifier could be omitted. However, we will put the public interface part of the class first and the hidden private details last. 3. Although not commonly done, a class may have several private and public sections; the keywords private: and public: mark the beginning of each. b. Access (i) A particular instance of a class is called an : ClassName object_name; (ii) Private members can be accessed (except by functions described later). (iii) Public members can be accessed. ClassName object_name; To access them outside the class, one must use the : c. Where are class declarations placed? Usually in a header file whose name is ClassName.h. The library is then called a.
3 III. Classes III-3 2. Example: Declaring a class Time Version 1 /** Time.h This header file defines the data type Time for processing time. Basic operations are: Set: To set the time Display: To display the time */ #include <iostream> using namespace std; class Time /******** Member functions ********/ /* Set sets the data members of a Time object to specified values. * See Fig. 3.1 for documentation */ void Set( ); /* Display displays time in standard and military format using * output stream out. * See Fig. 3.1 for documentation */ void Display( ) ; /********** Data Members **********/ unsigned, ; char ; // 'A' or 'P' unsigned ; // military time equivalent ; // end of class declaration Notes: 1. The "my" in names of data members is simply to remind us of the "I-can-do-it-myself" nature of a class object. 2. The const at the end of Display()'s prototype makes it a, which means that. It is good practice to protect the data members in this way from accidental modification.
4 III-4 III. Classes 3. Why not make all members public? So they. Why? Otherwise programmers may use them in programs, other classes, libraries, However, the to improve storage, simplify algorithms for operations, etc., and all programs, classes, that access them directly must then be modified. Therefore: Always define data members of a class as private. Keeping the data members "hidden" forces programs to interact with an object through its, which thus provide the then programs that use an object will not require change. between programs and the class. If this interface does not change, 3. Implementation of a Class Usually, only the prototypes of the member functions are placed inside the class declaration to definitions are outside. However, when a declaration of some public item such as a type, constant, or function is inside a class declaration another name for "function prototype" is "function declaration" and is then referenced or defined outside the class declaration, the compiler must be informed where the declaration/prototype is This is accomplished using the which has the form This is referred to as the or name of ItemName. Example: class Something public: const int CAPACITY = 100; typedef double ArrayType[CAPACITY]; void Print(ArrayType a, int itssize);
5 III. Classes III-5 Traditionally, definitions of member functions have been put in an implementation file ClassName.cpp corresponding to the class' header file. This is done to. (Unfortunately, the class data members, which store data and are therefore part of the implementation, must be in the.h file.) With the increasing use of, however, this practice is becoming less common because current compiler technology doesn't permit this split for templates everything has to be in the same file. Thus the reason for dropping the ".h" from standard class libraries. They're really class-template libraries, and there are therefore no corresponding ".cpp" file. 4. Example: Definitions of Member Functions for class Time Version 1 /** Time.cc -- implements the Time member functions **/ #include "Time.h" /*** Utility Functions -- Prototypes ***/ int ToMilitary(unsigned hours, unsigned minutes, char am_pm); //----- Function to implement the Set operation void (unsigned hours, unsigned minutes, char am_pm) // Check if (hours >= 1 && hours <= 12 && minutes >= 0 && minutes <= 59 && (am_pm == 'A' am_pm == 'P')) myhours = hours; myminutes = minutes; myamorpm = am_pm; mymiltime = ToMilitary(hours, minutes, am_pm); else cerr << "*** Can't set time with these values ***\n"; // Object's data members remain unchanged //----- Function to implement the Display operation void (ostream & out) const out << myhours << ':' << (myminutes < 10? "0" : "") << myminutes << ' ' << myamorpm << ".M. (" << mymiltime << " mil. time)";
6 III-6 III. Classes /*** Utility Functions -- Definitions ***/ /* ToMilitary converts standard time to military time. * * Receive: hours, minutes, am_pm * Return: The military time equivalent ********************************************************/ int ToMilitary (unsigned hours, unsigned minutes, char am_pm) if (hours == 12) hours = 0; return hours * minutes + (am_pm == 'P'? 1200 : 0); 5. Testing the class // Test driver #include <iostream> using namespace std; int main() cout << "We'll be eating at "; cout << endl; Execution: We'll be eating at 5:30 P.M. (1730 military time) Again, note the difference from the procedural approach. Rather than package up the object and send it off to some function for processing, we To set my digital watch to 5:30 P.M., I don't wrap it up and mail it off to Casio and have them do it; rather, I push a button! To display the time, I don't wrap up my watch and mail if off to Casio and have them tell me what time it is. Ridiculous! I have it display the time to me itself, perhaps pushing a button to turn on the backlight so I can see it.
7 III. Classes III-7 6. Some Notes a. Member functions: "Inside" an object so don't pass object to them as a parameter. Another way to view this: They receive the class object to be operated on implicitly, rather than explicitly via a parameter. Non-member functions: "Outside" an object, so to operate on an object, they must receive it via a parameter. b. Public items like types and constants declared inside a class declaration must be qualified with the class name when used outside the class: ClassName::ItemName Constants are usually specified to be static so this is a global class property that can be accessed by all objects of that class type rather than having each such object carry around it's own copy of that constant. c. Nontrivial member functions: Usually: Prototypewithin the class Define outsided the class; must qualify their names: ClassName::FunctionName() d. Simple member functions: Usually: Specify that it be an function, which suggests to the compiler that it with parameters replaced by arguments, thus avoiding the usual overhead of a function call. This can be done in two ways: 1. Prototype the function inside the class declaration as usual, but its name as usual: In ClassName.h class ClassName // Public section -- function members ReturnType SimpleFunction(param_list); // Private section -- data members ; ReturnType ClassName::SimpleFunction(param_list) // function body
8 III-8 III. Classes 2. Simply In this case, it need not be prototyped, its name need not be qualified, and the compiler will treat it as an inline function: In ClassName.h class ClassName // Public section -- function members ReturnType SimpleFunction(param_list) // function body // Private section -- data members ; But use this method only for simple functions to avoid interface clutter. d. In Set(), we tested whether the arguments are valid: if (hours >= 1 && hours <= 12 && minutes >= 0 && minutes <= 59 && (am_pm == 'A' am_pm == 'P')) myhours = hours; myminutes = minutes; else This is to ensure that the following class invariant is true: This class invariant is intended to guarantee that the so that other function members can be sure of this Thus, whenever an operation modifies any of the data members, we should always check that. An alternative way to test this is to use the during debugging which: Accepts a boolean condition; If that condition is true, execution continues as usual. If the condition is false, execution halts and an error message is displayed. #include using namespace std; //----- Function to implement the Set operation mechanism (from <cassert> at least void Time::Set(unsigned hours, unsigned minutes, char am_pm) (hours >= 1 && hours <= 12 && minutes <= 59 && (am_pm == 'A' am_pm am_pm == 'P')); myhours = hours; myminutes = minutes;
9 III. Classes III-9 Testing: If we change driver.cpp as: mealtime.set(13, 30, 'P'); execution terminates with the following message: Time.cpp :11: failed assertion `hours >= 1 && hours <= 12 && minutes <= 59 && (am_pm == 'A' am_pm == 'P')' IOT trap A third alternative is to that the calling function can and take appropriate action //----- Function to implement the Set operation void Time::Set(unsigned hours, unsigned minutes, char am_pm) // Check class invariant if (hours >= 1 && hours <= 12 && minutes >= 0 && minutes <= 59 && (am_pm == 'A' am_pm == 'P')) else To catch this exception, a calling function might contain mealtime.set(13, 30, 'P'); cout << "This is a valid time\n"; cout << "ERROR: " << badtime << endl; exit(-1); cout << "Proceeding\n"; When executed, the output produced will be ERROR: *** Illegal initializer values ***
10 III-10 III. Classes 7. Class Constructors a. Recall that constructing an object consists of: (1) for the object, and (2) the object. In our example, after the declaration Time mealtime; memory has been allocated for mealtime, but it's data members are not initialized (and are likely to contain "garbage" values). It would be better if: the programmer could specify initial values for mealtime default values were used if no initial values are specified. b. This can be accomplished using. Properties: (1) Their primary role (for now) is to of an object with values (either default values or values provided as arguments) (2) Their names are always the same as the. (3) They are always function members and are (almost always) prototyped in the public section. (4) They do not return a value; they have (not even void). For this reason, documentation that describes their behavior commonly specify: 1. What values they receive (if any) via parameters: 2. Preconditions: Conditions that must be true before the function is called. and 3. Postconditions: Conditions that must be true when the function terminates. (5) Often they are quite simple and can be inlined in either of the two ways escribed earlier. (6) Constructors get called (7) If no constructor is given in the class, which allocates memory and initializes it with some default (possibly garbage) value. A default constructor is one that is used when the declaration of an object contains no initial values: ClassName object_name; (8) If we supply a constructor for a class, then we must also provide a default constructor.
11 III. Classes III-11 c. Example: Constructors for Time class In Time.h class Time /******** Member functions ********/ public: /***** Class constructors *****/ /* --- Construct a class object (default). * Precondition: A Time object has been declared. * Postcondition: The Time object is initialized to 12:00 A.M.; * that is, the myhours, myminutes, and myamorpm * members are initialized to 12, 0, 'A', respectively, * and mymiltime to 0. **********************************************************************/ /* --- Construct a class object (explicit values). * Precondition: A Time object has been declared. * Receive: Initial values inithours, initminutes, and * initampm * Postcondition: The myhours, myminutes, and myamorpm members * of thetime object are initialized to inithours, * initminutes, and initampm, respectively, and * mymiltime to the corresponding military time. **********************************************************************/ // other member function prototypes /********** Data Members **********/ private: ; // end of class declaration or
12 III-12 III. Classes class Time /******** Function Members ********/ public: /***** Class constructors *****/ /* --- Construct a class object (default) */ Time() myhours = 12; myminutes = 0; myamorpm = 'A'; mymiltime = 0; /* --- Construct a class object (explicit values) */ // other member function prototypes /********** Data Members **********/ private: ; // end of class declaration Add to Time.cpp #include <cassert> using namespace std; //----- Function to implement the explicit-value constructor (unsigned inithours, unsigned initminutes, char initampm) // Check class invariant assert(inithours >= 1 && inithours <= 12 && initminutes >= 0 && initminutes <= 59 && (initampm == 'A' initampm == 'P')); myhours = ; myminutes = ; myamorpm = ; mymiltime = ToMilitary(initHours, initminutes, initampm);
13 III. Classes III-13 Testing # 1 Time mealtime, bedtime(11,30,'p'); Creates and initializes 2 Time objects: Default Constructor Explicit-Value Constructor mealtime myhours myminutes myamorpm mymiltime Member functions bedtime myhours myminutes myamorpm mymiltime Member functions mealtime.display(cout); cout << endl; bedtime.display(cout); cout << endl; Execution: 12:00 A.M. (0 mil. time) 11:30 P.M. (2330 mil. time) Testing # 2 Time mealtime, bedtime(13,0,'p'); Execution: Time.cpp:12: failed assertion `inithours >= 1 && inithours <= 12 && initminutes <= 59 && (initampm == 'A' initampm == 'P')' IOT trap Note: We could combine both constructors into a single constructor function by using : Replace constructors in Time.h with: /* --- Construct a class object. Precondition: A Time object has been declared. Precondition: A Time object has been declared. Receive: Initial values inithours, initminutes, and initampm (defaults 12, 0, 'A') Postcondition: The myhours, myminutes, and myamorpm members of the Time object are initialized to inithours, initminutes, and initampm, respectively */
14 III-14 III. Classes Testing: Time mealtime, t1(5), t2(5, 30), t3(5, 30, 'P'); Creates 4 Time objects: mealtime myhours myminutes myamorpm mymiltime Member functions t1 myhours myminutes myamorpm mymiltime Member functions t2 myhours myminutes myamorpm mymiltime Member functions t3 myhours myminutes myamorpm mymiltime Member functions Execution: mealtime.display(cout); cout << endl; 12:00 A.M. (0 mil. time) t1.display(cout); cout << endl; 5:00 A.M. (500 mil. time) t2.display(cout); cout << endl; 5:30 A.M. (530 mil. time) t3.display(cout); cout << endl; 5:30 P.M. (1730 mil. time) Question: What happens with the declaration Time t(5, 'P'); Will it create Time object t with values 5, 0, 'P' in its data members? All parameters with default arguments must appear after all parameters without default arguments. 9. Copy Operations Two default copy operations are provided: 1. Copy in 2. Copy in Each makes a (byte-by-byte) copy of the data members of the object. Examples: Both: 1. Allocate memory for t 2. Copy data members of bedtime into them so t is a copy of bedtime : t bedtime myhours myminutes myamorpm mymiltime P 2330 Time t = myhours myminutes myamorpm mymiltime P 2330 also does: Right side calls the explicit-value constructor to construct a (temporary) Time object and then copies it into t. Note: These are not assignments; a default is called.
15 III. Classes III-15 There is a default copy operation for assignment. Example: copies the members of mealtime into t, replacing any previous values: t myhours myminutes myamorpm 12 0 A mymiltime 0 mealtime myhours myminutes myamorpm 12 0 A mymiltime 0 9. Access (Extractor) Functions Data members are private; they cannot be accessed outside the class. It is often necessary, however, to make the values stored in some or all of these members accessible. For this, access (or extractor) member functions can be provided. Example: Problem: To add extractors to class Time: (We will do this only for the myhours member; the others are essentially the same.) Specification: Receives: Returns: As usual, the specification tells us how to prototype the function: If we declare it as a member function, then it will be "inside" the Time object and so no parameters (Time or otherwise) will be needed. The function returns myhours, which is an integer. In addition, because this function simply retrieves the value stored in a data member, it is simple enough to. Also because it does not modify any data members it should be prototyped (and defined) as a function. Add to Time.h class Time /********** Data Members **********/ /******** Member functions ********/ public: /***** Data Retrievers *****/ /* Hour Accessor * Receive: The Time object containing this function (implicitly) * Return: The value stored in the myhours member of the Time * object containing this function *****************************************************************/ // and similar functions for myminutes, myamorpm, and mymiltime retrieval
16 III-16 III. Classes /********** Data Members **********/ private: ; // end of class declaration //----- Definition of Hour() inline unsigned Time::Hour() const; Testing: Time mealtime; Execution: cout << "Hour: " << mealtime.hour() << endl; Hour: Output and Input Overloading Operators Friend Functions Add output operation to a class early so that it can be used for debugging. It is convenient to overload operator<< for a Time object so we can write instead of cout << "We'll be eating at " << mealtime << endl; cout << "We'll be eating at " ; mealtime.display(cout); cout << endl; a. Overloading operators: In C++, operator can be implemented with the function If a member function of a class C, and a is of type C, the compiler treats a b as If not a member function of a class C the compiler treats a b as b. Overloading Output Operator << Can operator<<() be a member function? No, because the compiler will treat cout << t as which would mean that operator<<() would have to be a member of class ostream! Putting the prototype ostream & operator<<(ostream & out, const Time & t); inside the class declaration causes a compiler error like: `Time::operator <<(ostream &, const Time &)' must take exactly one argument because making operator<<() a member function of Time means that it already has the Time object containing it as an (implicit) parameter, so it can't have two more.
17 III. Classes III-17 Option 1: Put its prototype in the header file Time.h but outside the class declaration. and it's definition in Time.cpp Actually, because it is so simple, we inline it by putting it's definition in Time.h: class Time public: // documentation omitted to save space here Time(); Time(unsigned inithours, unsigned initminutes, char initampm); int Hour() const return myhour; int Minute() const return myminute; char AMPM() const return myamorpm; int MilTime() const return mymiltime; void Display(ostream & out); private: unsigned myhours, myminutes; char myamorpm; // 'A' or 'P' unsigned mymiltime; // military time equivalent ; // end of class declaration /* --- operator<< displays time in standard and military format using ostream out. Receives: An ostream out and a Time object t Output: The time represented by the Time object t Passes back: The ostream out with t inserted into it. Return value: out */ Why 1st parameter a reference parameter? The ostream gets modified so must be passed back. Why 2nd parameter a const reference parameter? To avoid the overhead of having to copy a class object. Why return a reference to out? So we can. For example: cout << t1 << endl << t2 << endl; Because << is, this is evaluated as Output So first function must return so expression becomes which is evaluated as 5:00 A.M. (500 mil. time) 5:30 A.M. (530 mil. time)
18 III-18 III. Classes Option 2: Replace Display() with operator<< : Replace the prototype of Display() in Time.h class Time public: ; /***** I/O Functions *****/ /* --- operator<< displays time in standard and military format using ostream out. Receives: An ostream out and a Time object t Output: The time represented by t Passes back: The ostream out with representation of t inserted into it. Return value: out */ ostream & operator<<(ostream & out, const Time & t); And replace the definition of Display() in Time.cpp //----- Function to implement ostream output ostream & operator<<(ostream & out, const Time & t) out << t.myhours << ':' << (t.myminutes < 10? "0" : "") << t.myminutes << ' ' << t.myamorpm << ".M. (" << t.mymiltime << " mil. time)"; return out; A function that a class names as a friend is a: to which the class has granted permission to. Note: Because a friend function is not a function member: It's definition is not qualified using the class name and the scope operator (::). It receives the time object on which it operates as a parameter It uses the dot operator to access the data members. b. Input To add an input operator to our Time class, we proceed in much the same way as for output. We could either: 1. Add a member function ReadTime() that reads values and stores them in the data members of a Time object; then call it from non-member function operator>>() 2. Declare operator>>() to be a friend function so that it can access the data members of a Time object and store input values in them.
19 III. Classes III-19 In our original version of this new data type, we had two other basic operations, comparing two Times to determine if one is less than another, and advancing a Time by a given number of hours and minutes. We will now consider how these can be added to the class. 10. Adding Relational Operators: We will describe how to add only one of the relational operators less than the others are similar. Specification: Receives: Two Time objects Returns: True if the first Time object is less than the second; false otherwise. Question: Should it be a member function? Question to help in deciding: Should it be inside the Time class from where it can operate on the Time object that contains it and another external Time object or should it be outside the class from where it can operate on any two Time objects? Answer: Either will work, but in keeping with the OOP "I-can-do-it-myself" principle of making objects selfcontained, we usually opt for using member functions whenever possible. In this case, we might better rephrase our specification as: Receives: Returns: A Time object (and the current object implicitly) True if I (the Time object containing this function) am less than the time object received; false otherwise. Add to Time.h: /***** Relational operators *****/ /* --- operator< determines if one Time is less than another Time Receive: A Time t (and the current object implicitly) Return: True if time represented by current object is < t */ Because of the simplicity of this function we inline it in either of the two ways described earlier; for example, put it's inlined definition after the end of the class declaration in Time.h: ; // end of class declaration
20 III-20 III. Classes For the external perspective:... class Time public: // member functions... /***** Relational operators *****/ /* --- operator< determines if one Time is less than another Time Receive: Two Times t1 and t2 Return: True if time t1 is less than time t2/ */ ; // end of class declaration 12. Adding Increment/Decrement Operators: Specification: Receives: Returns: A Time object (perhaps implicitly) The Time object with minutes incremented by 1 minute. Question: Should it be a member function? Yes Add to Time.h: /***** Increment operator *****/ /* --- Advance() increments a Time by 1 minute. Receive: Current time object (implicitly) Pass back: The Time object with its minutes incremented by */ void Advance(); Add to Time.cpp: //----- Function to implement Advance() void Time::Advance() myminutes++; myhours += myminutes / 60; myminutes %= 60; if (mymiltime == 1159) myamorpm = 'P'; else if (mymiltime == 2359) myamorpm = 'A'; // else no change mymiltime = ToMilitary(myHours, myminutes, myamorpm);
21 III. Classes III-21 We could overload operator++() but how do we distinguish between prefix ++ and postfix ++? Solution: In C++, operator++() with no parameters is prefix operator++(int) with one int parameter is postfix [The int parameter is not used in the definition.] 13. Problem of Redundant Declarations A class like Time might be used in a program, libraries, other class libraries, and so it could easily happen that it gets included several times in the same file e.g., Program needs Time class, so it #includes "Time.h" Program also needs library Lib, so it #includes "Lib.h" but Lib.h also #includes "Time.h" This would cause "redeclaration" errors during compiling. How do we prevent the declarations in Time.h from being included more than once in a file? Use Wrap the declarations in Time.h inside preprocessor directives like the following: [The preprocessor scans through a file removing comments, #including files, and processing other directives (which begin with #)before the file is passed to the compiler.] : : Usually the name of the class in all caps The first directive tests to see whether the identifier TIME has been defined. If it has not: Processing proceeds to the second directive, which defines TIME (to be 1), and then continues on through what follows and on to the #endif and beyond. If it has been defined: The preprocessor removes all code that follows until a #elif, #else, of #endif directive is encountered. Thus, the first time the preprocessor encounters a class declaration like Time, it defines the name TIME. If it encounters the class declaration again, since TIME has been defined, all code between #ifndef TIME and #endif is stripped, thus removing the redeclaration.
Introduction & Review
CPSC 250 Data Structures Introduction & Review Dr. Yingwu Zhu What to learn? ADT design & implementation using C++ class Algorithm efficiency analysis Big-O ADTs: Binary search trees, AVL trees, Heaps,
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationIV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard
IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationIntroduction Of Classes ( OOPS )
Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! Needed for Boggle assignment! We are starting to see a little bit in MarbleBoard assignment as well 2 Classes in
More information7.1 Optional Parameters
Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationOperator overloading
1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The
More informationEECE.3220: Data Structures Spring 2017
EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More informationObject Oriented Design
Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More informationADTs & Classes. An introduction
ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object
More informationOperator Overloading
Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions.... 2 2 I/O Operators 4 3 Comparison Operators 6 3.1 Equality Operators....... 11 3.2 Less-Than Operators...... 13 1 1 Operators
More informationQUIZ. What are 3 differences between C and C++ const variables?
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments
More informationIntermediate Programming & Design (C++) Classes in C++
Classes in C++ A class is a data type similar to a C structure. It includes various local data (called data members) together with constructors, destructors and member functions. All of them are called
More informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationSTUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationLab 2: ADT Design & Implementation
Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted
More informationAbstraction in Software Development
Abstract Data Types Programmer-created data types that specify values that can be stored (type of data) operations that can be done on the values The user of an abstract data type (ADT) does not need to
More informationObject Oriented Programming COP3330 / CGS5409
Object Oriented Programming COP3330 / CGS5409 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors Object -- an encapsulation of data
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationMakefiles Makefiles should begin with a comment section of the following form and with the following information filled in:
CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationPreview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++
Preview Object Oriented Programming with C++ Class Members Inline Functions vs. Regular Functions Constructors & Destructors Initializing class Objects with Constructors C++ Programming Language C Programming
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationpointers & references
pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using
More informationInput And Output of C++
Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout
More informationReference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that
Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationAppendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.
A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators
More informationl A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND
Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Fall 2016 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains
More informationIntroduction to Classes
Introduction to Classes Procedural and Object-Oriented Programming Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationLecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47
Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College October 25, 2017 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Function Details Assert Statements
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
More informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-2: Programming basics II Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428 March
More informationUEE1302 (1102) F10: Introduction to Computers and Programming
Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,
More information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
More informationObject-Oriented Design (OOD) and C++
Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign
More information2. It is possible for a structure variable to be a member of another structure variable.
FORM 1(put name, form, and section number on scantron!!!) CS 162 Exam I True (A) / False (B) (2 pts) 1. What value will the function eof return if there are more characters to be read in the input stream?
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2012 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationReview: C++ Basic Concepts. Dr. Yingwu Zhu
Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to
More informationCS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()
More informationObject Oriented Design
Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following
More information1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!
//Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2015 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationCHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object
CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationMore About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil
More About Classes Gaddis Ch. 14, 13.3 CS 2308 :: Fall 2015 Molly O'Neil Pointers to Objects Just like pointers to structures, we can define pointers to objects Time t1(12, 20, true); Time *tptr; tptr
More informationChapter 13: Introduction to Classes Procedural and Object-Oriented Programming
Chapter 13: Introduction to Classes 1 13.1 Procedural and Object-Oriented Programming 2 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a
More informationSFU CMPT Topic: Classes
SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables
More informationChapter 9 Classes : A Deeper Look, Part 1
Chapter 9 Classes : A Deeper Look, Part 1 C++, How to Program Deitel & Deitel Fall 2016 CISC1600 Yanjun Li 1 Time Class Case Study Time Class Definition: private data members: int hour; int minute; int
More informationClasses: A Deeper Look
Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationl A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND
Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Spring 2017 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationDistributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes
Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented
More informationA Deeper Look at Classes
A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by
More informationUniversity of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.
University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.
More informationAbstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles
Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More informationDue Date: See Blackboard
Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.
More informationPIC 10A Objects/Classes
PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
More informationObject Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year
Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures
More informationStarting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,
Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class
More informationME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types
ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming Data is stored in variables CS 2308 Spring 2014 Jill Seaman - Perhaps using arrays and structs. Program is a collection of functions that perform
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationMidterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationSoftware Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example
Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell
More informationCS 247: Software Engineering Principles. ADT Design
CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More information! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform
Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Fall 2013 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform
More informationPaytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value
Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! (cont.) Last time we did a BankAccount class (pretty basic) This time we will do something more like the classes
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationC++ for Python Programmers
C++ for Python Programmers Adapted from a document by Rich Enbody & Bill Punch of Michigan State University Purpose of this document This document is a brief introduction to C++ for Python programmers
More informationstatic CS106L Spring 2009 Handout #21 May 12, 2009 Introduction
CS106L Spring 2009 Handout #21 May 12, 2009 static Introduction Most of the time, you'll design classes so that any two instances of that class are independent. That is, if you have two objects one and
More informationIntroduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.
Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and
More informationTypes, Values, Variables & Assignment. EECS 211 Winter 2018
Types, Values, Variables & Assignment EECS 211 Winter 2018 2 Road map Strings and string I/O Integers and integer I/O Types and objects * Type safety * Not as in object orientation we ll get to that much
More informationOBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2
More informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More informationArizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373
Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Overview Object Creation Control Distribution Possibilities Impact of design decisions on IP control 2 Good
More informationCOMP322 - Introduction to C++ Lecture 01 - Introduction
COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this
More information