Arizona s First University. ECE 373. Operation Overloading. The Revolution Operation Will Be Televised (and, these slides will be online later today)
|
|
- Sibyl Sparks
- 6 years ago
- Views:
Transcription
1 Arizona s First University. ECE 373 Operation Overloading The Revolution Operation Will Be Televised (and, these slides will be online later today)
2 Previously, on ECE373 Families of operators can be overloaded in C++ Provide a natural look and feel for object behaviors in text Upsides: Easy to read, understand, code, for some operators Downsides Enforcement sometimes made by signature, not always enforceable (we cannot guarantee that subtraction/addition is done correctly) Some contracts made (informally) are not always kept (remember: call your parent function s operator=) Operator [ ] Some operators used in multiple fashions Hard to learn all of the crazy signatures Common uses int array[5]; // Declaring an array array[2] = 10; // Assigning to index int j = array[3]; // Assigning from index 2
3 What s in a signature? retval Class::operator ( const Class& obj ) retval Class::operator ( const Class& obj ) const retval& Class::operator ( const Class& obj ) retval operator ( Class obj ) retval& operator ( Class obj ) 6. const retval& Scope::operator ( ) const These potential signatures are a contract between the interface designer, and the user Consider: example 2 the final const means that the function operator cannot modify the state of the Object the const inside the argument list, means that only const operations can be called on the obj Consider: example 6 the returned const retval object can only receive const operations 3
4 Families of operators Refer to Table 8-1 in the text Ones we will use the most: access: [ ] manipulation: +, -, *, /, ++, --, <<, >>, % bitwise comparison: ^, &,, ~ streaming*: <<, >> assignment: +=, -=, *=, /= unary: ++, --, - comparison in whole: <, >, ==, = * The signature of the function determines the difference between manipulation and streaming 4
5 Starting example: MyInteger // lec17-example1.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::string tostring( ) { std::stringstream result; result << value; return result.str( ); } protected: int value; }; // lec17-example1.cpp #include "lec17-example1.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; a=b; std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; return EXIT_SUCCESS; } 1. Does it compile? 2. What s the result??? 5
6 Example 1: results Scanning dependencies of target lec17-example1 [ 93%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example1.dir/lec17-example1.cpp.o Linking CXX executable lec17-example1 macphee-2:build sprinkle$./src/lectures/lec17/lec17-example1 a=0 b=10 a=10 b=10 macphee-2:build sprinkle$ 6
7 Example 2: Twist // lec17-example2.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::string tostring( ) { std::stringstream result; result << value; return result.str( ); } protected: int value; }; // lec17-example2.cpp #include "lec17-example2.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; //a=b; a=7; std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; return EXIT_SUCCESS; } 1. Does it compile? 2. What s the result??? 7
8 Ha Ha Scanning dependencies of target lec17-example2 [ 94%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example2.dir/lec17-example2.cpp.o Linking CXX executable lec17-example2 macphee-2:build sprinkle$./src/lectures/lec17/lec17-example2 a=0 b=10 a=7 b=10 macphee-2:build sprinkle$ 8
9 Why does it compile? Conversion constructors are constructors that can be called with a single argument. It specified a conversion from the type of its first argument to the type of its class (i.e., the class to which the constructor belongs). // the MyInteger is created by the // compiler as a temporary object a = MyInteger(7); The conversion is applied implicitly when the compiler deems it is needed unless the explicit modifier is used when declaring the constructor. class MyInteger { public: explicit MyInteger( int i=0 ) : value( i ) { }... } 9
10 Example 3: Explicit Constructors // lec17-example3.h #include <cstdio> #include <sstream> class MyInteger { public: explicit MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::string tostring( ) { std::stringstream result; result << value; return result.str( ); } protected: int value; }; // lec17-example3.cpp #include "lec17-example3.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; b = MyInteger(7); a=b; a=7; std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; return EXIT_SUCCESS; } 1. Does it compile? 2. What s the result??? 10
11 Scanning dependencies of target lec17-example3 [ 94%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example3.dir/lec17-example3.cpp.o /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example3.cpp: In function int main() : /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example3.cpp:18: error: no match for operator= in a = 7 /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example3.h:12: note: candidates are: MyInteger& MyInteger::operator=(const MyInteger&) make[2]: *** [src/lectures/lec17/cmakefiles/lec17-example3.dir/lec17-example3.cpp.o] Error 1 make[1]: *** [src/lectures/lec17/cmakefiles/lec17-example3.dir/all] Error 2 make: *** [all] Error 2 macphee-2:build sprinkle$ Of course, we could fix even this by defining MyInteger& operator=( int other ) { value = other; } Use explicit as a keyword, if you want to prevent conversion construction (e.g., if the compiler has an error in that there are two potential operations that conflict) 11
12 Starting with the operators // lec17-example4.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::string tostring( ) { std::stringstream result; result << value; return result.str( ); } // add two MyIntegers together MyInteger operator+( const MyInteger& rhs ) { MyInteger result; result.value = rhs.value + value; return result; } protected: int value; }; // lec17-example4.cpp #include "lec17-example4.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; MyInteger c; c = a+b; std::cout << "c=" << c.tostring( ) << std::endl; return EXIT_SUCCESS; } 1. Does it compile? 2. What s the result??? 12
13 Scanning dependencies of target lec17-example4 [100%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example4.dir/lec17-example4.cpp.o Linking CXX executable lec17-example4 [100%] Built target lec17-example4 macphee-2:build sprinkle$./src/lectures/lec17/lec17-example4 a=0 b=10 c=10 macphee-2:build sprinkle$ 13
14 Do the twist // lec17-example5.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::string tostring( ) { std::stringstream result; result << value; return result.str( ); } // add two MyIntegers together MyInteger operator+( const MyInteger& rhs ) { MyInteger result; result.value = rhs.value + value; return result; } protected: int value; }; 1. Does it compile? 2. What s the result??? // lec17-example5.cpp #include "lec17-example5.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; MyInteger c,d; a = b + 7; // option 1 std::cout << "a=" << a.tostring( ) << std::endl; c = 10 + a; // option 2 std::cout << "c=" << c.tostring( ) << std::endl; d = ; // option 3 std::cout << "d=" << d.tostring( ) << std::endl; return EXIT_SUCCESS; } 14
15 Example 5: Result Scanning dependencies of target lec17-example5 [100%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example5.dir/lec17-example5.cpp.o /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example5.cpp: In function int main() : /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example5.cpp:20: error: no match for operator+ in 10 + a make[2]: *** [src/lectures/lec17/cmakefiles/lec17-example5.dir/lec17-example5.cpp.o] Error 1 make[2]: Target `src/lectures/lec17/cmakefiles/lec17-example5.dir/build' not remade because of errors. make[1]: *** [src/lectures/lec17/cmakefiles/lec17-example5.dir/all] Error 2 make[1]: Target `all' not remade because of errors. make: *** [all] Error 2 make: Target `default_target' not remade because of errors. 15
16 What s the problem? The compiler isn t smart enough to call a conversion constructor on 10, because there is such a huge number of things that take int objects as constructors Conversion constructors really only work when they are called with an L-value // example L-value calls a = b + 7; // -> a.operator=( b.operator+( 7 ) ) d = ; // -> d.operator=( MyInteger( 10+7 ) ) // example NON L-value calls c = 10 + a; // -> c.operator=( 10 + a );???? So, not all operators are class members, some are global functions that are declared as friend functions We discuss next, which ones, and why... 16
17 Operators as class members CLASS &operator=(const CLASS &src); CLASS &operator&=(const CLASS &src); CLASS &operator =(const CLASS &src); CLASS &operator^=(const CLASS &src); CLASS &operator+=(const CLASS &src); CLASS &operator-=(const CLASS &src); CLASS &operator*=(const CLASS &src); CLASS &operator++(void);//prefix operator Need to use our state Logically take a right-hand side as an argument Do not (always) have to return by reference: CLASS operator++(int);//postfix operator CLASS operator-(void) const; Any operator that REQUIRES an l-value is better implemented as a member function. This shows that it can ONLY be invoked on existing, modifiable, objects. 17
18 The pre/postfix operator Remember these good times? #include <cstdio> #include <iostream> int main( void ) { std::cout << "Postfix ============" << std::endl; for( int i=0; i<10; i++ ) { std::cout << "in, i=" << i++ << std::endl; } } std::cout << "Prefix ============" << std::endl; for( int i=0; i<10; i++ ) { std::cout << "in, i=" << ++i << std::endl; } Postfix ============ in, i=0 in, i=2 in, i=4 in, i=6 in, i=8 Prefix ============ in, i=1 in, i=3 in, i=5 in, i=7 in, i=9 18
19 Pre/Post So, why the difference in the two signatures, anyway? CLASS &operator++(void);//prefix operator CLASS operator++(int);//postfix operator The postfix operator returns the current value, and in the meantime, we change our state. The prefix operator returns the new value, and simultaneously changes our state. So, THIS doesn t make sense, right? CLASS &operator++(void) const;//prefix operator CLASS operator++(int) const;//postfix operator 19
20 Ways to remember (some) semantics Pre/post (just showed): Remember which one changes state NOW Negate: does not change state...you need to say x = -x, and you do not need any kind of parameter value CLASS operator-(void) const; ALL assignment operators return this* (duh...), and do not need to change the state of what is passed in CLASS &operator=(const CLASS &src); CLASS &operator&=(const CLASS &src); CLASS &operator =(const CLASS &src); CLASS &operator^=(const CLASS &src); CLASS &operator+=(const CLASS &src); CLASS &operator-=(const CLASS &src); CLASS &operator*=(const CLASS &src); 20
21 Operators as friend functions friend CLASS operator (const CLASS &lhs, const CLASS &rhs); friend CLASS operator&(const CLASS &lhs, const CLASS &rhs); friend CLASS operator^(const CLASS &lhs, const CLASS &rhs); friend bool operator==(const CLASS &lhs, const CLASS &rhs); friend bool operator=(const CLASS &lhs, const CLASS &rhs); friend bool operator>(const CLASS &lhs, const CLASS &rhs); friend bool operator<(const CLASS &lhs, const CLASS &rhs); friend CLASS operator~(const CLASS &src); friend CLASS operator*(const CLASS &lhs, const CLASS &rhs); friend CLASS operator+(const CLASS &lhs, const CLASS &rhs); friend CLASS operator-(const CLASS &lhs, const CLASS &rhs); friend CLASS operator<<(const CLASS &lhs, unsigned int n_bits); friend CLASS operator>>(const CLASS &lhs, unsigned int n_bits); friend ostream &operator<<(ostream &out, const CLASS &src); friend istream &operator<<(istream &in, CLASS &dst); Why do these need to be FRIEND functions? y = x; 21
22 Friend function operators Use conversion constructors to find an appropriate operator overload to perform the operation You don t know which argument will be converted, so you create a non-member function that can be called by the compiler, and make it your friend, so it can play with your, uh, I mean, use your parts. Conversion constructors Create a class from another data type (int, etc.) Useful for things like y = x Any operator that does not require an l-value and is commutative is better implemented as a non-member function (+,-, etc.). This allows the compiler to apply a conversion in case of argument mismatch for the first argument. 22
23 A final note on conversions // lec17-example6.cpp #include "lec17-example6.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; int j; // what happens here? j = b; return EXIT_SUCCESS; } 23
24 Conversion functions // lec17-example6.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::string tostring( ) { std::stringstream result; result << value; return result.str( ); } // converts this class into an int operator int( ) { return value; } protected: int value; }; // lec17-example6.cpp #include "lec17-example6.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a.tostring( ) << std::endl; std::cout << "b=" << b.tostring( ) << std::endl; int j; // what happens here? j = b; return EXIT_SUCCESS; } 24
25 Example 6: Results Scanning dependencies of target lec17-example6 [100%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example6.dir/lec17-example6.cpp.o Linking CXX executable lec17-example6 [100%] Built target lec17-example6 macphee-2:build sprinkle$./src/lectures/lec17/lec17-example6 a=0 b=10 j=10 macphee-2:build sprinkle$ 25
26 Overloading stream operators (<<) // lec17-example7.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } std::ostream &operator<<( std::ostream& out, const MyInteger& rhs ) { out << rhs.value; return out; } // converts this class into an int operator int( ) { return value; } protected: int value; }; // lec17-example7.cpp #include "lec17-example7.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a << std::endl; std::cout << "b=" << b << std::endl; int j; // what happens here? j = b; std::cout << "j=" << j << std::endl; return EXIT_SUCCESS; } 26
27 Uh oh, what did we do wrong? Scanning dependencies of target lec17-example7 [100%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example7.dir/lec17-example7.cpp.o In file included from /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example7.cpp:3: /Users/sprinkle/work/teaching/ece373/src/lectures/lec17/lec17-example7.h:17: error: std::ostream& MyInteger::operator<<(std::ostream&, const MyInteger&) must take exactly one argument make[2]: *** [src/lectures/lec17/cmakefiles/lec17-example7.dir/lec17-example7.cpp.o] Error 1 make[1]: *** [src/lectures/lec17/cmakefiles/lec17-example7.dir/all] Error 2 make: *** [all] Error 2 friend ostream &operator<<(ostream &out, const CLASS &src); Ah, right...yeah, there s a reason to pay attention to that kind of stuff. 27
28 Example 8: operator<< done right // lec17-example8.h #include <cstdio> #include <sstream> class MyInteger { public: MyInteger( int i=0 ) : value( i ) { } ~MyInteger( ) { } MyInteger( const MyInteger& other ) : value( other.value ) { } MyInteger& operator=( const MyInteger& other ) { value = other.value; } friend std::ostream &operator<<( std::ostream& out, const MyInteger& rhs ) { out << rhs.value; return out; } // converts this class into an int operator int( ) { return value; } protected: int value; }; // lec17-example8.cpp #include "lec17-example8.h" #include <iostream> int main( void ) { MyInteger a,b(10); std::cout << "a=" << a << std::endl; std::cout << "b=" << b << std::endl; int j; // what happens here? j = b; std::cout << "j=" << j << std::endl; return EXIT_SUCCESS; } 28
29 Example 8: Results [100%] Building CXX object src/lectures/lec17/cmakefiles/lec17-example8.dir/lec17-example8.cpp.o Linking CXX executable lec17-example8 [100%] Built target lec17-example8 macphee-2:build sprinkle$./src/lectures/lec17/lec17-example8 a=0 b=10 j=10 macphee-2:build sprinkle$ 29
Overloaded Operators, Functions, and Students
, Functions, and Students Division of Mathematics and Computer Science Maryville College Outline Overloading Symbols 1 Overloading Symbols 2 3 Symbol Overloading Overloading Symbols A symbol is overloaded
More informationMore Advanced Class Concepts
More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators
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 informationVectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects
Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in
More informationShahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods
Overloading Operators friend functions static data and methods Shahram Rahatlou Computing Methods in Physics http://www.roma1.infn.it/people/rahatlou/cmp/ Anno Accademico 2018/19 Today s Lecture Overloading
More informationChapter 18 - C++ Operator Overloading
Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend
More informationCSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms
CSC 330 Object Oriented Programming Operator Overloading Friend Functions & Forms 1 Restrictions on Operator Overloading Most of C++ s operators can be overloaded. Operators that can be overloaded + -
More informationOverloading & Polymorphism
Overloading & Polymorphism Overloading is considered ad-hoc polymorphism. 1 Can define new meanings (functions) of operators for specific types. Compiler recognizes which implementation to use by signature
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 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 informationReview. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?
Review Describe pass-by-value and pass-by-reference Why do we use pass-by-reference? What does the term calling object refer to? What is a const member function? What is a const object? How do we initialize
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 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 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 informationCh. 12: Operator Overloading
Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42
More informationAbstraction and Encapsulation. Benefits of Abstraction & Encapsulation. Concrete Types. Using Typedefs to streamline classes.
Classes II: Type Conversion,, For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Abstraction and Encapsulation Abstraction: Separation of interface from
More informationThe University Of Michigan. EECS402 Lecture 15. Andrew M. Morgan. Savitch Ch. 8 Operator Overloading Returning By Constant Value
The University Of Michigan Lecture 15 Andrew M. Morgan Savitch Ch. 8 Operator Overloading Returning By Constant Value Consider This Program class ChangePocketClass public: ChangePocketClass():quarters(0),dimes(0)
More informationA <Basic> C++ Course
A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation
More informationA <Basic> C++ Course
A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor Operator overloading
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 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 informationOperator Overloading in C++ Systems Programming
Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading
More informationG52CPP C++ Programming Lecture 17
G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions
More informationPIC10B/1 Winter 2014 Exam I Study Guide
PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand
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 informationEINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science
EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.
More informationChapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 8 Operator Overloading, Friends, and References Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Basic Operator Overloading Unary operators As member functions Friends
More informationOverloading Operators in C++
Overloading Operators in C++ C++ allows the programmer to redefine the function of most built-in operators on a class-by-class basis the operator keyword is used to declare a function that specifies what
More informationProgram construction in C++ for Scientific Computing
1 (26) School of Engineering Sciences Program construction in C++ for Scientific Computing 2 (26) Outline 1 2 3 4 5 6 3 (26) Our Point class is a model for the vector space R 2. In this space, operations
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 informationCSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia New exercise posted yesterday afternoon, due Monday morning - Read a directory
More informationIntroduction. W8.2 Operator Overloading
W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction
More informationOperator Overloading
Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is
More informationOBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded
More informationW8.2 Operator Overloading
1 W8.2 Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. as friend Functions Overloading Stream Insertion and Extraction
More informationClasses in C++98 and C++11
Classes in C++98 and C++11 January 10, 2018 Brian A. Malloy Slide 1 of 38 1. When we refer to C++98, we are referring to C++98 and C++03, since they differ only slightly. C++98 contained 3 types of constructors,
More informationCSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning
More informationOperator overloading. Instructor: Bakhyt Bakiyev
Operator overloading Instructor: Bakhyt Bakiyev content Operator overloading Operator Overloading CONCEPT: C++ allows you to redefine how standard operators work when used with class objects. Approaches
More informationOperator Overloading
Operator Overloading Introduction Operator overloading Enabling C++ s operators to work with class objects Using traditional operators with user-defined objects Requires great care; when overloading is
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationOperator overloading. Conversions. friend. inline
Operator overloading Conversions friend inline. Operator Overloading Operators like +, -, *, are actually methods, and can be overloaded. Syntactic sugar. What is it good for - 1 Natural usage. compare:
More informationSet Implementation Version 1
Introduction to System Programming 234122 Set Implementation Version 1 Masha Nikolski, CS Department, Technion 1 // Version 1.0 2 // Header file for set class. 3 // In this implementation set is a container
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer
More informationCS304 Object Oriented Programming Final Term
1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing
More informationCS11 Intro C++ Spring 2018 Lecture 5
CS11 Intro C++ Spring 2018 Lecture 5 C++ Abstractions C++ provides rich capabilities for creating abstractions class Complex { double re, im; public: Complex(double re, double im);... ; Would be nice if
More informationCh 8. Operator Overloading, Friends, and References
2014-1 Ch 8. Operator Overloading, Friends, and References May 28, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel
More informationCSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 2 Yusuf Pisan Compiled helloworld yet? Overview C++ fundamentals Assignment-1 CSS Linux Cluster - submitting assignment Call by Value,
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 informationSlide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary
Slide Set 14 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2016 ENCM 339 Fall 2016 Slide Set 14 slide 2/35
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 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 Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer June 3, 2013 OOPP / C++ Lecture 9... 1/40 Const Qualifiers Operator Extensions Polymorphism Abstract Classes Linear Data Structure Demo Ordered
More informationProgramming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 6 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Friends 2 Friends of Objects S Classes sometimes need friends. S Friends are defined outside
More informationIII. Classes (Chap. 3)
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,
More informationMore class design with C++ Starting Savitch Chap. 11
More class design with C++ Starting Savitch Chap. 11 Member or non-member function? l Class operations are typically implemented as member functions Declared inside class definition Can directly access
More informationSee the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I
Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const
More informationDetermine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array
Recursion review Thinking recursion: if I know the solution of the problem of size N-, can I use that to solve the problem of size N. Writing recursive routines: Decide the prototype Can formulate both
More information4 Strings and Streams. Testing.
Strings and Streams. Testing. 21 4 Strings and Streams. Testing. Objective: to practice using the standard library string and stream classes. Read: Book: strings, streams, function templates, exceptions.
More informationClasses and Operators. Ali Malik
Classes and Operators Ali Malik malikali@stanford.edu Game Plan Recap Classes II Operator Overloading Announcement Recap Objects We use objects all the time (string, vector etc.) Objects encapsulate behaviour
More informationAnd Even More and More C++ Fundamentals of Computer Science
And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members
More informationStacks and their Applications
Stacks and their Applications Lecture 23 Sections 18.1-18.2 Robb T. Koether Hampden-Sydney College Fri, Mar 16, 2018 Robb T. Koether Hampden-Sydney College) Stacks and their Applications Fri, Mar 16, 2018
More informationProgramming in C++: Assignment Week 4
Programming in C++: Assignment Week 4 Total Marks : 20 March 22, 2017 Question 1 Using friend operator function, which set of operators can be overloaded? Mark 1 a.,, , ==, = b. +, -, /, * c. =,
More information14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members
Chapter 14: More About Classes 14.1 Instance and Static Members Instance and Static Members instance variable: a member variable in a class. Each object has its own copy. static variable: one variable
More informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
More informationPHY4321 Summary Notes
PHY4321 Summary Notes The next few pages contain some helpful notes that summarize some of the more useful material from the lecture notes. Be aware, though, that this is not a complete set and doesn t
More informationCSE 333 Midterm Exam July 24, Name UW ID#
Name UW ID# There are 6 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,
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 informationProgrammazione. Prof. Marco Bertini
Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking
More informationSFU CMPT Topic: Class Templates
SFU CMPT-212 2008-1 1 Topic: Class Templates SFU CMPT-212 2008-1 Topic: Class Templates Ján Maňuch E-mail: jmanuch@sfu.ca Monday 3 rd March, 2008 SFU CMPT-212 2008-1 2 Topic: Class Templates Class templates
More informationLecture 3 ADT and C++ Classes (II)
CSC212 Data Structure - Section FG Lecture 3 ADT and C++ Classes (II) Instructor: Feng HU Department of Computer Science City College of New York @ Feng HU, 2016 1 Outline A Review of C++ Classes (Lecture
More informationCOMP6771 Advanced C++ Programming
1........ COMP6771 Advanced C++ Programming Week 4 Part Three: Function Objects and 2016 www.cse.unsw.edu.au/ cs6771 2........ Converting Class Types to bool Convenient to use a class object as bool to
More informationProgramming in C and C++
Programming in C and C++ 6. C++: Operators, Inheritance, Virtual Methods Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair
More informationCSE 333 Lecture 9 - intro to C++
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The
More informationKOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday
More informationJan 27, C++ STL Streams. Daniel Maleike
C++ STL Streams Why Stream-IO? The STL way for I/O Input, output, formatting, file access More type-safe than printf(), scanf() Extensible with user defined types (classes) Inheritable, i.e. custom I/O
More informationCircle all of the following which would make sense as the function prototype.
Student ID: Lab Section: This test is closed book, closed notes. Points for each question are shown inside [ ] brackets at the beginning of each question. You should assume that, for all quoted program
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 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 informationOperator overloading: extra examples
Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationInformatik I (D-ITET) Übungsstunde 11, Hossein Shafagh
Informatik I (D-ITET) Übungsstunde 11, 4.12.2017 Hossein Shafagh shafagh@inf.ethz.ch Problem 10.1. Recursive Function Analysis Problem 10.1. Recursive Function Analysis (a) bool f (const int n) { if (n
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More informationCopying Data. Contents. Steven J. Zeil. November 13, Destructors 2
Steven J. Zeil November 13, 2013 Contents 1 Destructors 2 2 Copy Constructors 11 2.1 Where Do We Use a Copy Constructor? 12 2.2 Compiler-Generated Copy Constructors............................................
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationOperator Overloading
C++ Programming: Operator Overloading 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Operator overloading Basics on operator overloading Overloading operators as
More informationFinancial computing with C++
Financial Computing with C++, Lecture 11 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 11 - p2/24 Outline Derived classes
More informationModule Operator Overloading and Type Conversion. Table of Contents
1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading
More information2.9 DCL58-CPP. Do not modify the standard namespaces
2.9 DCL58-CPP. Do not modify the standard namespaces Namespaces introduce new declarative regions for declarations, reducing the likelihood of conflicting identifiers with other declarative regions. One
More informationDue Date: See Blackboard
Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with
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 informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
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 informationMastering Data Abstraction or Get nit-picky on design advantages
Arizona s First University. Mastering Data Abstraction or Get nit-picky on design advantages Luke: Your not my father! Vader: You mean, You re not my father Luke: What? Vader: You used the possessive,
More informationOperator Dot Wording
2016-10-16 Operator Dot Wording Bjarne Stroustrup (bs@ms.com) Gabriel Dos Reis (gdr@microsoft.com) Abstract This is the proposed wording for allowing a user-defined operator dot (operator.()) for specifying
More informationAIMS Embedded Systems Programming MT 2017
AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors
More information18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors
590 18. Dynamic Data Structures I Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors Recap: vector 591 Can be initialised with arbitrary size n 591 Recap: vector
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 informationProtection Levels and Constructors The 'const' Keyword
Protection Levels and Constructors The 'const' Keyword Review: const Keyword Generally, the keyword const is applied to an identifier (variable) by a programmer to express an intent that the identifier
More information