IT533 Adapted from Textbook (SAVITCH) and Lecture Notes (PUSATLI), 2014.

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Additional Topics Chapter 10 Programming with Classes.
Advertisements

Operator overloading redefine the operations of operators
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Introduction to Programming Lecture 39. Copy Constructor.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
Review of C++ Programming Part II Sheng-Fang Huang.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 25P. 1Winter Quarter C++: I/O and Classes Lecture 25.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Dynamic memory allocation and Pointers Lecture 4.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
C++ Basics. Compilation What does compilation do? g++ hello.cpp g++ -o hello.cpp hello.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
CS Object Oriented Programming Using C++
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
1 Lecture 17 Operator Overloading. 2 Introduction A number of predefined operators can be applied to the built- in standard types. These operators can.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Operator Overloading What is operator overloading? Most predefined operators (arithmetic, logic, etc.) in C++ can be overloaded when applied to objects.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Bill Tucker Austin Community College COSC 1315
Yan Shi CS/SE 2630 Lecture Notes
Hank Childs, University of Oregon
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
What Actions Do We Have Part 1
Chapter 1.2 Introduction to C++ Programming
By Muhammad Waris Zargar
Introduction to Programming
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Overloading Operator MySting Example
Chapter 2 part #1 C++ Program Structure
Chapter 2 part #3 C++ Input / Output
group work #hifiTeam
Concepts and Basics of C++ Programming
Lecture 8 – 9 Arrays with in a class
Dynamic Memory Allocation Reference Variables
Chapter 2 Elementary Programming
Programming Funamental slides
Operator Overloading.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3: Input/Output
Variables T.Najah Al_Subaie Kingdom of Saudi Arabia
Object Oriented Programming Using C++
CS150 Introduction to Computer Science 1
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
What Actions Do We Have Part 1
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Chapter 2 part #3 C++ Input / Output
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Pointers and dynamic objects
Review of Function Overloading
Class rational part2.
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

IT533 Adapted from Textbook (SAVITCH) and Lecture Notes (PUSATLI), 2014

Friend Function An ordinary function However, it is not a member function It can access private members of objects It is a public function no matter where it is declared. Most of them are overload operands but any function can be a friend function.

Syntax Use keyword “friend” in front. “ClassName::” is not used. A function is accepted as a “friend” to a class; hence, “friend” keyword is put only in the function declaration, not in the function definition.

Example void print (Integer &in) { cout<<"number = "<<in.number; } class Integer{ private: int number; public: Integer (int n=0):number(n){} friend void print(Integer&); }; main(){ Integer in(1); print(in); system("pause");

Example #include<iostream> using namespace std; class Integer{ int number; public: Integer (int n=0):number(n){} friend void print(Integer&); }; void print (Integer &in) { cout<<"number = "<<in.number; } main(){ Integer in(1); print(in); // NOT in.print() as print is not a member function system("pause");

Example main(){ #include <iostream> Complex c1(1.1, 2.2), c2(3.3, 4.4); Complex c3=add(c1,c2); c3.print(); system("pause"); } #include <iostream> using namespace std; class Complex{ float real; float imag; public: Complex(float=0.0, float=0.0); void print(){cout <<real<<"+"<<imag<<"i"<<endl;} friend Complex add(Complex&, Complex&); }; Complex::Complex(float r, float i): real(r), imag(i){} Complex add(Complex &c1, Complex &c2){ return Complex(c1.real+c2.real, c1.imag+c2.imag); }

Exercise Write a program that can multiply a matrix of 4x4 by a vector of 4 elements and gives the product. e.g. b0= a00v0+ a01v1+ a02v2+ a03v3 a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23 a30 a31 a32 a33 v0 v1 v2 v3 b0 b1 b2 b3 = X

The this Pointer The this pointer is a predefined pointer that points to the calling object. this is not the name of the calling object; it is the name of a pointer that points to the object. It may look like useless but sometimes it may be handy.

The this Pointer The class objects maintain their own data members; however, they share a single copy of each member function stored in the memory. Following example is a re-coding by using this pointer while calling a member function.

Example Both codes will generate same output. #include <iostream> using namespace std; class MyNumber{ public: int t; void print(){ cout<< t <<endl; } }; main(){ MyNumber n1; n1.t=5; n1.print(); system("pause"); #include <iostream> using namespace std; class MyNumber{ public: int t; void print(){ cout<< this->t <<endl; } }; main(){ MyNumber n1; n1.t=5; n1.print(); system("pause"); Both codes will generate same output.

Example #include <iostream> using namespace std; class MyNumber{ private: int number; public: MyNumber (int n=0){number=n;} MyNumber increment(int n){ number+=n; return MyNumber(number); } void print(){ cout<<"number = "<<number<<endl; }; … MyNumber& increment(int n){ number+=n; return *this; } main(){ MyNumber n1(1); n1.increment(2).increment(3).print(); system("pause"); }

Dynamic Memory Allocation Dynamic Variables are: variables created by the new operator created and destroyed while the program is running

new By using new operator, a pointer can be used to refer to a variable even if the variable has no identifiers to name it. new operator serves to acquire a memory space at execution time. int *ptr; ptr = new int; OR int *ptr = new int;

Example class Rational{ int x; public: void display() {...} }; main(){ Rational *rptr; // OR Rational *rptr=new Rational; rptr=new Rational; rptr->display(); }

Uses Dynamic memory allocation is used to: allocate and initialize a dynamic object allocate space for multiple dynamic objects int *ip = new int(12); Rational *rp=new Rational(3,4); Rational *rlist =new Rational[5]; rlist[1].display();

Uses Dynamic memory allocation is used to: delete a dynamic object delete multiple dynamic objects char *ptr1 = new char(‘A’); char *ptr2=ptr1; delete ptr1; cout<<*ptr2; // ERROR! employee *ptr=new employee[10]; delete [] ptr;

Example What is the output? #include <iostream> using namespace std; class Ex{ int *n; public: Ex(int=0); ~Ex(); void print(){ cout<<*n<<endl; } }; Ex::Ex(int i){ n=new int(i); Ex::~Ex(){ delete n; main(){ Ex obj1(5), obj2; obj1.print(); obj2.print(); system("pause"); } What is the output?

Static Class Data Members When you declare a data member in a class, all the objects of that class has a copy of that data member as its own. However, you can declare a data member to be shared by all instances i.e. across all instances of the class.

Example #include <iostream> using namespace std; class KeepCount{ static int counter; // static declaration // ‘counter’ is global to all instances public: KeepCount() {counter=counter+1;} void print(){cout <<"counter = " <<counter<<endl;} }; int KeepCount::counter=0; // static definition main(){ KeepCount kc1, kc2, kc3; kc1.print(); kc2.print(); system("pause"); } Example // WHAT IF … main(){ KeepCount kc1, kc2, kc3; kc1.print(); kc2.print(); KeepCount *ptr=new KeepCount; system("pause"); }

Operator Overloading This is to assign new functions to existing operators For example: addition (+) The operator “+” is functional for integer type; but it is functional for double type as well. Because it is already overloaded

Properties Operator overloading functions can be member or friend functions All operators can be overloaded except . .* :: ?: () and []  operators can only be overloaded as member functions Only existing operators can be overloaded Operator overloading does NOT give additional functionality to the code

Example You would like to use addition operator (+) for complex numbers as well. #include <iostream> using namespace std; class Complex{ float real, imag; public: Complex (float r, float i){real=r; imag=i;} friend Complex operator+(Complex&, Complex&); void print(){cout <<real <<"+"<<imag<<"i"<<endl;} }; /* Operator overloading as a friend function */ Complex operator+(Complex &a, Complex &b){ return Complex(a.real+b.real, a.imag+b.imag); } main(){ Complex x(2,3), y(5,8); Complex z=x+y; z.print(); system("pause"); }

Example Overload += operator for complex numbers #include<iostream> using namespace std; class Complex{ float real, imag; public: Complex(float r, float i){real=r; imag=i;} void print(){cout <<real <<"+"<<imag<<"i"<<endl;} void operator +=(Complex&); }; /* Operator overloading as a member function */ void Complex::operator+=(Complex &a){ real=real+a.real; imag=imag+a.imag; } main(){ Complex x(2,3), y(5,4); x+=y; x.print(); int a=7; a+=2; cout<<a<<endl; a+=y; //ERROR! system("pause"); }

Overloading Operators with Objects #include<iostream> using namespace std; class A{ int number; public: int n1; A(){number=0; cout<<"default constructor"<<endl; } A(A &a){ number=a.number; cout<<"copy constructor"<<endl; ~A(){ cout<<"destructor"<<endl; A& operator= (A &a) { cout<<“assignment“; return *this; } }; main(){ A a1; cout<<1<<endl; A a2(a1); cout<<2<<endl; A a3=a2; cout<<3<<endl; a2=a1; } default constructor 1 copy constructor 2 3 assignment destructor

Briefly on Streams A stream is a flow of characters (including numbers). If this flow is into the program then it is an input stream. If the flow is out of the program then is an output stream. cin is an input stream connected to the keyboard. cout is an output stream connected to the screen.

Briefly on Streams ostream is a class, which provides output method (function). To call this method, you need an object of that class. cout is an object of the class ostream Similarly, cin is an instantiation of the class istream, which provides input method. << and >> are the operators to call those methods i.e. functions.

Overloading Input/Output You can overload << and >> operators to handle I/O for your own personal data type, such as objects of your class. For example, you may like to print data members of an object to the screen by using cout<<. To do this, you have to overload the operator <<.

Example #include <iostream> #include <String> using namespace std; class Name{ friend ostream& operator << (ostream&, Name&); friend istream& operator >> (istream&, Name&); private: string fName, lName; }; ostream& operator <<(ostream &os, Name &nm){ os<<"first name: " <<nm.fName<<endl; os<<"last name: " <<nm.lName<<endl; return os; } istream& operator >>(istream &inp, Name &nm){ cout<< "Enter first and last name: "; inp>>nm.fName>> nm.lName; return inp; main(){ Name myName; cin >>myName; cout <<myName; system("pause"); } Enter first and last name: Ali Kara first name: Ali last name: Kara Press any key to continue . . .

Example #include<iostream> using namespace std; class Complex{ double real, imag; public: Complex(double r=0, double i=0):real(r), imag(i){} friend ostream &operator<<(ostream&, Complex&); }; ostream &operator<< (ostream &stream, Complex &c){ stream<<c.real<<"+"<<c.imag<<"i"<<endl; return stream; } main(){ Complex c1(3,4); cout <<c1; system("pause"); 3+4i Press any key to continue . . .