CSC 1061 Week 03 ADT Classes with Operator Overloads PDF

Summary

This document provides lecture notes for CSC 1061, focusing on ADT classes and operator overloading in C++. The notes cover various concepts and examples related to these topics. Specific details include different parameter passing types and examples of operator overloading implementation.

Full Transcript

CSC 1061 ADT CLASSES WITH OPERATOR OVERLOADS OBJECTIVES AGENDA: WEEK 03 Correctly identify and use value 1. Type of Functions parameters, reference parameters and 2. Parameter passing types const reference parameters...

CSC 1061 ADT CLASSES WITH OPERATOR OVERLOADS OBJECTIVES AGENDA: WEEK 03 Correctly identify and use value 1. Type of Functions parameters, reference parameters and 2. Parameter passing types const reference parameters 3. Pass by Value | Pass by Ref Overload certain binary operators and input/output operators for new classes 4. Function Overloads and Polymorphism Identify the need for friend functions of a 5. Non-Member & Member functions new class and correctly implement such non-member functions 6. This pointer and static variables Explain the concept of operator 7. Operator Overloads overloading in C++, identify 8. Friend Functions overloadable operators, and implement custom behaviors for operators when used with user-defined classes TYPES OF FUNCTIONS IN C++ Function Type Description Example Non-Member A function that performs the int rand() Function task Member Function A function that performs the int std::string::size() const task on an object Overloaded Functions that perform same istream& getline(istream&, string&) Function task with same name, but istream& getline(istream, differ by argument list string, char) Operator Overload Operator extended to work string& operator+(string&, string&) Function with objects of a class Friend Function A non-member function can access the private and protected members of a class if it is declared a friend of that class. Template and To be discussed later this semester Recursive Function PARAMETER PASSING TYPES (CPLUSPLUS) Pass By Value (simple types): default when the function does NOT want to modify the parameter and the value is easy to copy (ints, doubles, char, bool, etc... simple types. NOT std::string) Pass By Reference (non-const) (simple types and objects): & value is expensive to copy AND/OR the function WANTS to modify the value referred to Const Pass by Reference (objects): const & value is expensive to copy AND the function does NOT want to modify the value referred to PASS BY VALUE PASS BY REFERENCE IN Only! IN and OUT Default way arguments are Address of: & passed into functions 1 X times the memory – points to Copy of the argument original variable 2 X times the memory Un-safe - can change original Safe because using a copy To ensure safety - const pass by More efficient way of passing reference & can be used in built-in datatypes like: More efficient way of passing in int, float, double, objects of classes like: char std::string EXAMPLE: PASS BY REF void swap(int& a, int& b); // 1 Prototype num1 num2 // pass by ref arguments int main() { 10 12 int num1 = 10, num2 = 12; swap(num1, num2); // 3 Call 0x3f 0xae return 0; } void swap(int& a, int& b) { // 2 Definition int tmp = a; a b a = b; b = tmp; 0x3f 0xae } FUNCTION OVERLOADS (CPLUSPLUS) Same function name Polymorphism Same task to complete Many forms of a Different number of arguments function Different data type of arguments Return Type cannot be a differing factor Parameter names cannot be a differing factor Many standard library functions are overloaded in C++. Update the program to the right and write a swap function that swaps two doubles. NON-MEMBER FUNCTION PROTOTYPE Non-member functions are stand-alone functions. All info is passed into the function and returned out of the function. The function prototype is the declaration Prototypes end in a ; and is declared in header files (.h) #ifndef MYFUNCTS_H #define MYFUNCTS_H #include // string class #include // toupper std::string strToUpper(const std::string&str); #endif NON-MEMBER FUNCTION DEFINITION BODY The non-member definition body begins with the prototype, minus the semi-colon, followed by the code block to perform the task. The arguments passed to the function are accessible within the function definition #include "myfuncts.h" std::string strToUpper(const std::string& str) { std::string tmp; for(char letter : str) tmp += toupper(letter); return tmp; } MEMBER FUNCTION PROTOTYPE A member function operates on any object of the class of which it is a member, and has access to all the members of a class for that object. Do NOT pass in the private data members to a member function prototype! Member functions already have access to everything within the class. #ifndef DATE_H #define DATE_H class Date { int day = 1, month = 1, year = 1970; public: std::string toString() const; // member }; #endif MEMBER FUNCTION DEFINITION BODY The definition body of the member function, will include the class:: attached to the function name, minus the semi-colon, followed by the code block to perform the task. Any of the private data members and the arguments passed to the function are accessible within the function definition. #include "date.h" std::string Date::toString() const { std::string strDate; strDate = std::to_string(month) + "/" + std::to_string(day) + "/" + std::to_string(year) + "\n"; return strDate; } CLASSES AND *THIS POINTER (GEEKSFORGEEKS) When an object calls a member function: the object gets its own copy of the data member. all objects access the same function definition using their copy of the data members. The this pointer is passed as a hidden argument to all member function calls and is available as a local variable this points to the object that invoked the member function call this is a pointer and stores the address of the object this pointer is NOT available in static member functions. Static member functions can be called without any object (with class name). STATIC VARIABLE (SHARED) (GEEKSFORGEEKS) The static member variable of a class are declared as static Static variables are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of same static variables for different objects. Static variables cannot be initialized using constructors. Note, most of our classes do not need shared variables between objects, but may need constant data between objects and thus a const static variable is created and initalized publicly. Change max to a constant static variable set to 24. POLYMORPHISM: OPERATOR OVERLOADS Starting with 1.12.3 Polymorphism section, read and complete all activities until the end of this tutorial page: Listings 2 to 7 Self-Check Exercises Q-11 to Q-14 OPERATOR OVERLOADING By overloading standard operators in a class, you can exploit the intuition of the users of that class. Can I define my own operators? NO, only built-in operators can be overloaded Here is the operator exceptions that cannot be overloaded:. (member selector) :: (scope-resolution) ?: (ternary) sizeof.* (member pointer selector) GUIDELINES OPERATOR OVERLOADING 1. By default, operators are ONLY automatically defined for simple data types (int, float, double, char). 2. Use common sense! Don’t overload an operator that is non-intuitive to your users. 3. If one relational operator is defined, define all 6: ==, !=, = 4. If you define arithmetic operators, maintain the usual arithmetic identities, and only provide mixed-mode (int and floats) operators when they make logical sense. Classes only provide assignment operator= automatically A copy of the object's values are created and assigned. HOW TODO OPERATOR OVERLOADING Left hand Operator Right hand Left and Right Type of operand operand operand types Operator Overload object1 == object2 same data type on Member OR either side Non-Member std::cout object2 same data type on Member OR either side Non-Member FRIEND FUNCTION DEFINITION (CPLUSPLUS) private and protected members of a class cannot be accessed from outside the class in which they are declared. This rule does not apply to "friends". Friends are functions or classes declared with the friend keyword. A non-member function can access the private and protected members of a class if it is declared a friend of that class. In the public section of the class, include a prototype declaration of the non-member function preceding it with the friend keyword. The definition body of the friend function, does NOT include the keyword friend and does NOT include class:: as it is a non-member function. OVERVIEW OPERATOR OVERLOADING Type Operator Overload Increment, ++, --, [] Member Decrement, Subscript Arithmetic *, /, +, -, % Non-Member Friend Relational ==, !=, = Member OR Comparison Non-Member Friend Operators Insertion and Non-Member Friend Extraction Assignment =, +=, -=, *=, /=, %= Member RELATIONAL OPERATOR OVERLOADS Don't be redundant! Operator Compliment Use compliments for code re-use == != 1. Define operator== explicitly < >= 2. Define operator< explicitly 3. operator!= { return !(lhObj == rhObj); } 4. operator>{ return !(lhObj rhObj); } OPERATOR FUNCTION EXAMPLE An operator completes the task as it does for the simple data type. int num = 10; Date dateObj(30, 9, 2023); std::cout

Use Quizgecko on...
Browser
Browser