Operator Overloading

Size: px
Start display at page:

Download "Operator Overloading"

Transcription

1 C++ Programming: Operator Overloading 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering

2 Contents Operator overloading Basics on operator overloading Overloading operators as top-level functions Overloading C++ operators I/O operators Assignment operators Special operators Memory management operators 2

3 Basics on Overloading What is overloading in C++ Refers to multiple definitions of the same name or symbol Types of C++ overloading Function overloading Multiple definitions for a top-level function name Method overloading Multiple definitions for a method name within a class Operator overloading Multiple definitions for an operator such as +, -, ++, Actually, an overloaded operator is a user-defined function (or method) that retains the convenience of operator syntax I.e., an operator can be overloaded as either a top-level function or a method 3

4 Examples of C++ Built-in Overloaded Operators Arithmetic operators Division OP / E.g.) int i = 2 / 3; float f = 2.0 / 3.0; // integer division // float division I/O operators Input OP >> and output OP << E.g.) cin >> i; cout << i; i >> 3 << 5; // originally defined as // bitwise shift OPs 4

5 C++ Operators That Can Be Overloaded new new[] delete delete[] + - * / % ^ & ~! = < > += -= *= /= %= ^= &= = << >> <<= >>= ==!= <= >= && ++ --,.* ->* -> () [] 5

6 Notices on C++ Operator Overloading Operators that can NOT be overloaded Member selection OP. Scope resolution OP :: Conditional OP? : E.g.) int i = (a > b)? a : b; Overloaded operators defined in the base class are inherited to its derived classes Operators NOT to be inherited: assignment OP = 6

7 Motivating Example Addition of two objects Suppose we have class C and two C objects Add two C objects and the result is another C object class C { public: C add(c& c) { ; C add(c& c1, C& c2) { // E.g. 2: function add a = add(b, c); C a, b, c; // E.g. 1: method C::add a = b.add(c); // overloaded + a = b + c; 7

8 Defining Overloaded Operator as a Method class C { public: C operator+(const C&) const; // declare + as a method named operator+ ; C C::operator+(const C& c) const { // implement the method in the usual way C a, b, c; a = b.operator+(c); // invoke method operator+ of b a = b + c; // == the method as an operator + Note that the 1st operand of + is object b whose method is invoked 8

9 Defining Operands as Parameters Overloading a binary operator A binary operator needs two operands a + b, a / b, a = b, The method has one parameter The 1st operand becomes the object whose method is invoked The 2nd operand becomes the single argument to the method Overloading a unary operator A unary operator needs just one operand!a, a++, &a, The method has no parameter The single operand becomes the object whose method is invoked 9

10 Operator Overloading Example 1 class C { public: // binary OP % C operator%(const C&); ; // unary OP! C operator!(); // void main() { C c1, c2, c3; c1 = c2 % c3; // same as // c1 = c2.operator%(c3); c1 =!c2; // same as // c1 = c2.operator!(); 10

11 Operator Overloading Example 2 // Class ordered pair class OPair { public: OPair(float f1 = 0.0, float f2 = 0.0) { p1 = f1; p2 = f2; bool operator==(const OPair&); private: float p1, p2; ; // Extends the definition of == // to compare OPair objects bool OPair::operator==(const OPair& s) { return (p1 == s.p1) && (p2 == s.p2); void main() { OPair s1(1, 2), s2(2, 1); if (s1 == s2) { // same as // s1.operator==(s2) 11

12 Operator Overloading Example 3 // Class Complex representing complex numbers class Complex { public: Complex(double r) : real(r), imag(0) { Complex(double r, double i) : real(r), imag(i) { Complex operator+(const Complex& c) { ; return Complex(real + c.real, imag + c.imag); // defines other operators and methods private: double real; double imag; // real part // imaginary part Complex c1(0), c2(1.0, 2.0), c3(2.0, 3.0); // c1 = 0.0, c2 = i, c3 = i c1 = c2 + c3; // c1 = c2 + c3 = i 12

13 Operator Overloading Example 4 class Foo { private: int bar; public: Foo(int val) { bar = val; bool operator==(const Foo& other) { return *this == other; Foo a(10), b(10); if (a == b) cout << Same objects. ; else cout << Different objects. ; // result? 13

14 Operator Syntax and Precedence Operator syntax and precedence do NOT change through overloading Number of operands E.g., if a built-in OP is unary, then all overloaded OPs are unary, if a built-in OP is binary, then all overloaded OPs are binary Occurrence of operands E.g., a unary OP that occurs before its operand must occur before its operand even when overloaded: a! (x), a~ (x), a* (x) Priority of operators E.g., priority of arithmetic operators: * always precedes + even when overloaded 14

15 Operator Overloading Example 5 int main() { // Class Complex defines overloaded OPs + and * that // have the same precedence as the original OPs Complex c1, c2, c3, ans; ans = c1 + c2 * c3; // is equivalent to // ans = c1 + (c2 * c3); class C { public: C operator%(); // ERROR: % is originally a binary OP 15

16 Overloading Operators as Top-Level Functions An overloaded operator can also be defined as a toplevel function class C { ; // overloaded operator + as a top-level function C operator+(const C& c1, const C& c2) { C a, b, c; // using overloaded operator + a = operator+(b, c); a = b + c; 16

17 Defining Operands as Parameters Overloading a binary operator A binary operator needs two operands a + b, a / b, a = b, The top-level function has two parameters The 1st operand becomes the 1st argument of the function The 2nd operand becomes the 2nd argument of the function Overloading a unary operator A unary operator needs just one operand!a, a++, &a, The top-level function has one parameter The single operand becomes the single argument 17

18 Notices on Operator Overloading Using Top-Level Functions An OP overloaded as a top-level function MUST include at least one class operand Otherwise, in some cases, the system could not distinguish between built-in OP and user-defined OP E.g., x + y : + is overloaded, but x and y are still ints (x) E.g., c1 + c2 : c1 and c2 are C objects, and + is overloaded for C Note memory management OPs need NOT include a class object argument (will be discussed later) E.g., new, new[], delete, and delete[] [], =, (), and -> OPs MUST be overloaded as methods to ensure that the 1st operand is a class object This prevents some expression errors from illegal syntax E.g., 9[obj], 6.32 = obj, 100(a, b), 3->obj 18

19 Operator Overloading Example 6 // ERROR: neither f1 nor f2 is a class object float operator%(int f1, int f2) { int a, b, c; a = b % c; // built-in % or overloaded %? // ERROR: [] must be overloaded as a method void operator[](int i, Point& s) { Point obj; 9[obj]; // illegal expression 19

20 Problem of OP Overloading with a Method class Complex { public: // convert constructors Complex(double r); Complex(double r, double i); // OP + as a method Complex operator+(const Complex& c1); ; void main() { Complex a(0), b(4.3, -8.2); a = b + 5.1; // OK: interpreted as // a = b.operator+(5.1) // by implicit type conv. // a = b.operator+(complex(5.1)) // by commutative law of + a = b; // ERROR: interpreted as // a = 5.1.operator+(b) 20

21 Solution to the Previous Problem Using a Top-Level Function class Complex { public: // convert constructors Complex(double r); Complex(double r, double i); ; void main() { Complex a(0), b(4.3, -8.2); a = b + 5.1; // OK: interpreted as // a = operator+(b, 5.1) // a = operator+(b,complex(5.1)) // OP + as a top-level func. Complex operator+( const Complex& c1, const Complex& c2) { a = b; // OK: interpreted as // a = operator+(5.1, b) // a = operator+(complex(5.1),b) 21

22 Problem of OP Overloading with a Top-Level Function Consider the following implementation of overloaded operator + in the previous example class Complex { public: private: double real; double imag; ; Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); What is the problem of the above example? 22

23 Solutions to the Previous Problem 1) Make real and imag public This explicitly violates information hiding of OO design principle 2) Use public accessor methods for real and imag A generic pattern for OO programming Preserves information hiding principle 3) Allow function operator+ to directly access real and imag Declare it as a friend function of class Complex 23

24 Operator Overloading Example 7: Using public Accessor Methods class Complex { public: Complex(double r, double i); double get_real() const { return real; double get_imag() const { return imag; private: double real; double imag; // Complex + OP as a top-level function Complex operator+(const Complex& t,const Complex& u) { return Complex(t.get_real() + u.get_real(), t.get_imag() + u.get_imag()); 24

25 friend Functions A class s private members are accessible only to its own methods and its friend functions Similarly, a class s protected members are accessible to its friend functions as well Note friend functions are NOT methods However, they are declared inside the class Thus, it can be prevented to access to critical data from suspicious and malicious codes via public accessor methods Nevertheless, it still violates strict interpretation of the OO design principle It is recommended to use friend functions carefully only for operator overloading 25

26 Operator Overloading Example 8: Using a friend Function class Complex { public: Complex(double r, double i); // friend function declaration friend Complex operator+(const Complex&, const Complex&); private: double real; double imag; // Complex + OP as a top-level function Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.real + c2.real, c1.imag + c2.imag); 26

27 Access Rights to Members Methods / Functions Access modifier public protected private Methods in the same class Methods in the same class hierarchy Methods in external classes or external functions friend functions 27

28 Overloading the I/O Operators By default, the system overloads bitwise shift operators ( >> and << ) as I/O operators for built in types By defining those operators as methods of basic I/O classes (basic_istream, basic_ostream) For formatted input of built-in types E.g.) cin >> i, where i is an int Interpreted as cin.operator>>(&i) Reads a value from the keyboard and stores it into i For formatted output of built-in types E.g.) cout << f, where f is a float Interpreted as cout.operator<<(f) Writes the value of f to the display 28

29 Overloading the I/O Operators (cont.) The I/O operators can be further overloaded for userdefined types The first operand of I/O operators belong to a system class e.g., >> is overloaded as basic_istream method To overload those I/O operators for user-defined types, it is required to modify system classes we should not do this, even if we could Thus I/O operators must be overloaded for a user-defined type as top-level functions Note that the overloaded I/O operators may need to be declared friend functions of the user-defined class 29

30 Example of Overloading >> class Complex { friend istream& operator>>(istream&, Complex&); // >> declared a friend of Complex ; istream& operator>>(istream& in, Complex& c) { return in >> c.real >> c.imag; // the istream is returned for chaining inputs Complex c_obj, c1_obj, c2_obj; cin >> c_obj; // operator>>(cin, c_obj) // cin >> c_obj.real >> c_obj.imag cin >> c1_obj >> c2_obj; // chain input (left-associative) // (cin >> c1_obj) >> c2_obj // cin >> c2_obj 30

31 Example of Overloading << class Complex { friend ostream& operator<<(ostream&, Complex&); // << declared a friend of Complex ; ostream& operator<<(ostream& out, Complex& c) { return out << c.real << + << c.imag << i << \n ; // the ostream is returned for chaining outputs Complex c_obj(1, 2), c1_obj(3, 4), c2_obj(5, 6); cout << c_obj; // operator<<(cout, c_obj) // 1+2i cout << c1_obj << c2_obj; // chain output (left-associative) // (cout << c1_obj) << c2_obj // cout << c2_obj 31

32 Overloading the Assignment Operator Copying objects belonging to the same class By copy constructor Create a new object by copying another object By assignment operator Copies an existing object to another object The system provides a copy constructor and an assignment operator for a class by default The compiler-provided ones simply copy each data member of the source object to the corresponding data member of the target object Programmers typically need to define ones for classes whose data members include pointers to dynamically allocated storages (refer to Section 3.5 for details) 32

33 Example of Compiler-Provided Assignment Operator class C { public: void set_x(int i) { x = i; void dump() const { cout << x << n ; private: int x; ; -999 int main() { -999 C c1, c2; c1.set_x(-999); c1.dump(); c2 = c1; // default assignment operator c2.dump(); 33

34 Problem of Compiler-Provided Assignment Operator class Namelist { public: Namelist(const Namelist&); Namelist(const string[], int); private: string* p; void copyintop(const Namelist&); ; Namelist::Namelist(const Namelist& d) : p(0) { copyintop(d); Namelist::Namelist(const string s[], int si) { p = new string[size = si]; for (int i = 0; i < size; i++) p[i] = s[i]; void Namelist::copyIntoP(const Namelist& d) { delete[] p; if (d.p!= 0) { p = new string[size = d.size]; for (int i = 0; i < size; i++) p[i] = d.p[i]; else { p = 0; size = 0; void main() { string list[] = {"Lab", "Husky", "Collie ; Namelist d1(list, 3), d2; d1.dump(); d2 = d1; d2.dump(); d2.set("great Dane", 1); d2.dump(); d1.dump(); 34

35 Before Overloading = Namelist d1(list, 3); d1.dump(); Lab Husky Collie Namelist d2; d2 = d1; d2.dump(); Lab Husky Collie copy d2.set( Great Dane, 1); d2.dump(); Lab Great Dane Collie d1.dump(); Lab Great Dane Collie 35

36 Example of Programmer-Written Assignment Operator class Namelist { public: Namelist& operator=( private: ; string* p; const Namelist&); void copyintop(const Namelist&); Namelist& Namelist::operator=( const Namelist& d) { if (this!= &d) copyintop(d); return *this; // for cascading void Namelist::copyIntoP(const Namelist& d) { delete[] p; if (d.p!= 0) { p = new string[size = d.size]; for (int i = 0; i < size; i++) p[i] = d.p[i]; else { p = 0; size = 0; void main() { string list[] = {"Lab", "Husky", "Collie ; Namelist d1(list, 3), d2; d1.dump(); d2 = d1; d2.dump(); d2.set("great Dane", 1); d2.dump(); d1.dump(); 36

37 After Overloading = The programmer s version of assignment operator Ensures that the new object and the original object have their own copies of the same data member p I.e., it does not simply copy d1.p to d2.p, but creates different storage for d2.p and then copies each element (string) in the storage to which d1.p points Namelist d2; d2 = d1; d2.set( Great Dane, 1); d2.dump(); Lab Great Dane Collie d1.dump(); Lab Husky Collie New copy Great Dane 37

38 Enabling Cascaded Assignment Note the programmer s version of overloaded assignment operator returns the pointer to the Namelist object itself (*this) to enable the cascaded assignment Namelist& Namelist::operator=(const Namelist& d) { if (this!= &d) copyintop(d); return *this; Namelist d1, d2, d3; d3 = d2 = d1; // = is right-associative // d3 = (d2 = d1) // means d3.operator=(d2.operator=(d1)) // d2 = d2 // means d3.operator=(d2) 38

39 Overloading Special Operators Special operators Subscriber operator [] E.g.) a[10] Function call operator () E.g.) setname( Kim ) Increment operator ++ E.g.) i++ or ++i Decrement operator -- E.g.) i-- or --i Type conversion operator Converts from a class type to some other type (i.e., reverse of convert constructor) 39

40 Overloading the Subscriber Operator The subscriber operator MUST be overloaded as a method With nonconst returntype: used to access and modify an object of returntype class C { returntype& operator[](paramtype); ; C arr; j = arr[i]; arr[i] = j; With const returntype: used to access, but not modify, an object of returntype class C { const returntype& operator[](paramtype); ; C arr; j = arr[i]; arr[i] = j; // *** error 40

41 Example of Array Bound Checking by Overloading [] class intarray { public: intarray(int s); int& operator[](int); int get_size() { return size; private: int size; int* a; ; intarray::intarray(int s) { try { a = new int[s]; catch(bad_alloc) { cerr << Unable to allocate storage for intarray\n ; throw; size = s; int& intarray::operator[](int i) { if (i < 0 i >= size) throw string( OutOfBounds ); return a[i]; void main() { intarray b(5); int i; try { OutOfBounds i = 5 for (i=0; i<b.get_size(); i++) b[i] = 2 * i; for (i = 0; i < 6; i++) cout << b[i] << \n ; catch (string s) { cerr << s << \n ; cerr << i = << i << \n ; 41

42 Overloading the Function Call Operator The function call operator also MUST be overloaded as a method class C { ; returntype operator()(paramtype1, paramtype2, ); E.g.) Suppose that paramtype1 = float and paramtype2 = string C c; c(12.3, Kim ); is interpreted as c.operator()(12.3, Kim ); 42

43 Example of 2D Array Bound Checking by Using Overloaded () Instead of accessing the cell at i, j using 2D subscriber OP [][], use overloaded function call OP () E.g., arr[i][j] arr(i, j) Method arr(i, j) accesses an item at cell (i * size2 + j) in the 1D representation of 2D array a Further, checks whether i and j is in bounds [2D array a] j(2) [1D representation of 2D array a] a[1][2] a[i][j]=a[i * size2 + j] i(1) size1 size1 * size2 size2 43

44 Example of 2D Array Bound Checking by Using Overloaded () (cont.) class inttwoarray { public: inttwoarray(int, int); int& operator()(int, int); private: int size1; int size2; int* a; ; inttwoarray::inttwoarray( int s1, int s2) { int size = s1 * s2; try { a = new int[size]; catch(bad_alloc) { cerr << Unable to allocate storage for inttwoarray\n ; throw; size1 = s1; size2 = s2; int& inttwoarray::operator() (int i, int j) { if (i < 0 i >= size1) throw string( 1st_OutOfBounds ); if (j < 0 j >= size2) throw string( 2nd_OutOfBounds ); return a[i * size2 + j]; void main() { inttwoarray b(3, 4); int i, j; for (i=0; i<b.get_size1(); i++) for(j=0; j<b.get_size2(); j++) b(i, j) = 2 * i + j; try { cout << b(1, 3) << '\n'; cout << b(4, 2) << '\n'; catch(string s) { cerr << s << '\n'; 5 1st_OutOfBounds 44

45 Overloading the Increment and Decrement Operators The increment ++ and decrement -- operators can also be overloaded Preincrement and predecrement operators (e.g., ++i) are declared without parameters returntype operator++() or returntype operator--() Postincrement and postdecrement operators (e.g., i++) are declared with a single int parameter returntype operator++(int) or returntype operator--(int) The int parameter just serves to distinguish postincremental OPs from preincremental OPs, thus, may NOT be used actually 45

46 Example of Overloaded Increment and Decrement Operators class Clock { public: Clock(int = 12, int = 0, int = 0); Clock tick(); friend ostream& operator<<( ostream&, const Clock&); Clock operator++(); // ++c Clock operator++(int); // c++ private: int hour; int min; int ap; // 0 is AM, 1 is PM ; Clock::Clock(int h,int m,int ap_f) { hour = h; min = m; ap = ap_f; Clock Clock::tick() { ++min; if (min==60) { hour++; min = 0; if (hour==13) hour = 1; if (hour==12 && min==0) ap =!ap; return *this; Clock Clock::operator++() { return tick(); Clock Clock::operator++(int n) { Clock c = *this; tick(); return c; ostream& operator<<(ostream& out, const Clock& c) { out <<setfill( 0 )<<setw(2) <<c.hour<< : <<setw(2)<<c.min; if (c.ap) out << PM ; else out << AM ; return out; int main() { Clock c, d; // default: 12:00 AM c = d++; cout << Clock c: << c << \n ; cout << Clock d: << d << \n ; Clock c: 12:00 AM Clock d: 12:01 AM 46

47 Overloading the Type Conversion Operator Recall that a convert constructor C(paramtype) converts type paramtype to class type C E.g., C(int): int type class type C Reversely, to convert a class type to another type, a type conversion operator can be used E.g., to convert class type C to othertype, declare a method of C such as operator othertype(); Note that the declaration does NOT include a return type, nevertheless, the method MUST return the converted value 47

48 Example of Using a Convert Constructor class C { C(int); ; // convert constructor int main() { int i = 8; C c; c = i; i = c; // == c.operator=(i) // by implicit type conversion // c.operator=(c(i)) // == c = C(i); // how about converting C obj to int? 48

49 Revisiting the Clock Example Amending the previous Clock class by adding a conversion operator to convert the time of a clock object to an integer time (a.k.a. military time ) class Clock { public: operator int(); // no return type declared ; void main() { Clock c(8, 55, 1); int i; i = c; // 08:55 PM 2055 Clock::operator int() { int time = hour; if (time == 12) time = 0; if (ap == 1) time += 12; time *= 100; time += min; return time; // returns converted value // though no return declared cout << c << \n ; cout << i << \n ; 08:55 PM

50 Notice on Using Type Conversion Operators Despite their convenience, type conversion operators should be used with caution Typically, the compiler (not the programmer) invokes a type conversion operator Thus, the normal call to a type conversion operator is hidden from the programmer, who may not have anticipated all of the situation in which the type conversion operator would be invoked char next; while (cin >> next) cout << next; // a type conversion operator handles the // conversion of the cin object to void* // if null (0), false, otherwise true 50

51 Overloading the Memory Management Operators The memory management operators (new, new[], delete, and delete[]) may be overloaded as either methods or top-level functions Useful for environments in which an application needs to take direct control over its own memory management E.g.) Embedded systems: having very limited memory resources E.g.) MS Windows: having memory management scheme that application programs are advised to follow Need NOT include a class object parameter when being overloaded The first parameter in the overloaded new or new[] MUST be of type size_t (the size of the object being created) The first parameter in the overloaded delete or delete[] MUST be of type void* (points to the storage to be freed) 51

52 Overloading the Memory Management Operators (cont.) // overloaded as method in class C void* C::operator new(size_t size) { // overloaded as top-level function void* operator new(size_t size) { // overloaded as method in class C void C::operator delete(void* objptr) { // overloaded as top-level function void operator delete(void* objptr) { 52

53 Example of Allocating Storage with Overloaded new Initial status Frame pool f = new Frame(); After the 1st memory request f 0 Free frame Free frame f = new Frame(); After the maxth memory request f 0 f 1 f max-1 53

54 Example of Allocating Storage with Overloaded new (cont.) const int MaxFrames = 4; const int DataSize = 128; class Frame { public: Frame() { name = NoName ; print(); Frame(const char* n) { name = n; print(); Frame(const string& n) { name = n; print(); Frame(const string&, const void*, unsigned); void print() const; void* operator new(size_t); private: string name; unsigned char data[datasize]; ; unsigned char framepool[maxframes*sizeof(frame)]; Frame* allframes=0; // no Frame yet bool alloc[maxframes]; // if alloc[i] is true ith storage // cell is allocated Frame::Frame(const string& n, const void* d, unsigned bsize) { name = n; memcpy(data, d, bsize); print(); void Frame::print() const { cout << name << created.\n ; 54

55 Example of Allocating Storage with Overloaded new (cont.) void* Frame::operator new(size_t size) { // allocating a new Frame? if (size!= sizeof(frame)) throw string( Not a Frame ): // storage allocated yet? if (allframes == 0) { allframes = reinterpret_cast <Frame*>(framePool); for (int i=0; i<maxframes; i++) alloc[i] = false; // finding a free storage cell for (int i=0; i<maxframes; i++) { if(!alloc[i]) { alloc[i] = true; return allframes + i; throw string( Out of Storage ); return 0; int main() { Frame* a[5]; string names[4] = { f1, f2, f3, f4 ; try { a[0] = new Frame; // the 1st Frame with NoName for(int i = 0; i < 4; i++) a[i+1] = new Frame(names[i]); // allocates Frames: the 1st // frame is already occupied catch(string s) { cerr << s << \n ; exit(exit_failure); return 0; NoName created. f1 created. f2 created. f3 created. Out of storage 55

56 Example of Allocating Storage with Overloaded new (cont.) framepool Initial status alloc[0] alloc[1] alloc[2] alloc[3] unsigned char[4 * sizeof(frame)] After the 1st new Frame() a[0] = allframes+0 allframes[0] name= NoName alloc[0] =True alloc[1] =False alloc[2] =False allframes[1] allframes[2] allframes[3] alloc[3] =False After the 4th new Frame( f3 ) allframes[0] name= NoName alloc[0] =True a[0] a[1] a[2] alloc[1] =True alloc[2] =True allframes[1] name= f1 alloc[3] =True allframes[2] name= f2 a[3] = allframes+3 allframes[3] name= f3 What about deletion? E.g.) delete a[2]; 56

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

CSC 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 information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

More Advanced Class Concepts

More 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 information

Operation Overloading.

Operation Overloading. Operation Overloading pm_jat@daiict.ac.in Recap: Why do we need Operator Overloading? Operator based expressions are more readable: Compare a + b * c with plus(a, times(b, c)) Recap: What is Operator Overloading?

More information

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Review. 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 information

Operator overloading. Instructor: Bakhyt Bakiyev

Operator 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 information

CS11 Intro C++ Spring 2018 Lecture 5

CS11 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 information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 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 information

Object oriented programming

Object oriented programming Exercises 6 Version 1.0, 21 March, 2017 Table of Contents 1. Operators overloading....................................................... 1 1.1. Example 1..............................................................

More information

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Reference 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 information

Operator overloading: extra examples

Operator 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 information

7.1 Optional Parameters

7.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 information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors 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 information

Program construction in C++ for Scientific Computing

Program 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 information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Overloading Operators in C++

Overloading 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 information

Ch. 12: Operator Overloading

Ch. 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 information

Object-Oriented Design (OOD) and C++

Object-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 information

Ch 8. Operator Overloading, Friends, and References

Ch 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 information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

CS3157: Advanced Programming. Outline

CS3157: 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 information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

Operator Overloading in C++ Systems Programming

Operator 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 information

Module Operator Overloading and Type Conversion. Table of Contents

Module 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 information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT 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 information

SFU CMPT Topic: Classes

SFU 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 information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN 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 information

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer

More information

CS304 Object Oriented Programming Final Term

CS304 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 information

Tokens, Expressions and Control Structures

Tokens, 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 information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

III. Classes (Chap. 3)

III. 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 information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract 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 information

Object-Oriented Principles and Practice / C++

Object-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 information

ADTs & Classes. An introduction

ADTs & 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 information

CS 247: Software Engineering Principles. ADT Design

CS 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 information

Overloaded Operators, Functions, and Students

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 information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software 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 information

Programming in C++ 5. Integral data types

Programming in C++ 5. Integral data types Programming in C++ 5. Integral data types! Introduction! Type int! Integer multiplication & division! Increment & decrement operators! Associativity & precedence of operators! Some common operators! Long

More information

Instantiation of Template class

Instantiation 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 information

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete. CMSC433, Fall 2001 Programming Language Technology and Paradigms Adam Porter Sept. 4, 2001 C++ without Classes Don t need to say struct New libraries function overloading confusing link messages default

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

2 ADT Programming User-defined abstract data types

2 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 information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT 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 information

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases. Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

More information

Chapter 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 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 information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

More class design with C++ Starting Savitch Chap. 11

More 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 information

Overloading & Polymorphism

Overloading & 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 information

Chapter 9. Operator Overloading. Dr Ahmed Rafat

Chapter 9. Operator Overloading. Dr Ahmed Rafat Chapter 9 Operator Overloading Overloading Operators Overloading Basics How Operators are Overloaded Arithmetic Operators Fstring Class Example Cast Operator Equality and Relational Operators Bitwise Operators

More information

A <Basic> C++ Course

A <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 information

Chapter 18 - C++ Operator Overloading

Chapter 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 information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See 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 information

A <Basic> C++ Course

A <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 information

Introduction. W8.2 Operator Overloading

Introduction. 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 information

Intermediate Programming & Design (C++) Classes in C++

Intermediate 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 information

Interview Questions of C++

Interview 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 information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

W8.2 Operator Overloading

W8.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 information

CONSTRUCTORS AND DESTRUCTORS

CONSTRUCTORS AND DESTRUCTORS UNIT-II CONSTRUCTORS AND DESTRUCTORS Contents: Constructors Default constructors Parameterized constructors Constructor with dynamic allocation Copy constructor Destructors Operator overloading Overloading

More information

Absolute C++ Walter Savitch

Absolute 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 information

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture: CISC 2200 Data Structure Fall, 2016 C++ Review:3/3 1 From last lecture: pointer type and pointer variable (stores memory addresses of a variable (of any type, local or global, automatic/static/dynamic)

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 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?

More information

Short Notes of CS201

Short 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 information

Introduction to C++ Systems Programming

Introduction 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 information

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

CS171:Introduction to Computer Science II

CS171:Introduction to Computer Science II CS171:Introduction to Computer Science II Department of Mathematics and Computer Science Li Xiong 1/24/2012 1 Roadmap Lab session Pretest Postmortem Java Review Types, variables, assignments, expressions

More information

C++ Programming: Inheritance

C++ Programming: Inheritance C++ Programming: Inheritance 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Basics on inheritance C++ syntax for inheritance protected members Constructors and destructors

More information

Fast Introduction to Object Oriented Programming and C++

Fast 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 information

Welcome 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. 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 information

pointers & references

pointers & 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 information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

The University Of Michigan. EECS402 Lecture 15. Andrew M. Morgan. Savitch Ch. 8 Operator Overloading Returning By Constant Value

The 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 information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

CS201 - Introduction to Programming Glossary By

CS201 - 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 information

For Teacher's Use Only Q No Total Q No Q No

For Teacher's Use Only Q No Total Q No Q No Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9

More information

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) Review Final exam Final exam will be 12 problems, drop any 2 Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) 2 hours exam time, so 12 min per problem (midterm 2 had

More information

Chapter 3. Numeric Types, Expressions, and Output

Chapter 3. Numeric Types, Expressions, and Output Chapter 3 Numeric Types, Expressions, and Output 1 Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and Explicit Type Conversion Calling a Value-Returning

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

KEY printed. Do not start the test until instructed to do so! CS 2704 Object-Oriented Software Design and Construction Test 1.

KEY printed. Do not start the test until instructed to do so! CS 2704 Object-Oriented Software Design and Construction Test 1. VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PROSI M UNI VERSI TY Instructions: Print your name in the space provided below. Answer each question in the space provided. If you want partial credit, justify

More information

Collected By Anonymous

Collected By Anonymous CS201- Introduction to Programming Mega Collection for Final Term Only Solved Paper Year Session Paper # 01 2012 Unknown Paper # 02 2011 (session_02) Paper # 03 2011 (session_03) Paper # 04 2010 Unknown

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Distributed 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 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 information

Chapter 2. Procedural Programming

Chapter 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 information

Variables and Operators 2/20/01 Lecture #

Variables and Operators 2/20/01 Lecture # Variables and Operators 2/20/01 Lecture #6 16.070 Variables, their characteristics and their uses Operators, their characteristics and their uses Fesq, 2/20/01 1 16.070 Variables Variables enable you to

More information

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Operator Overloading

Operator 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 information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. 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 information