Lecture 5 Constructors Operator Overloads “Absolute C++” Chapters 7.1,8.1,8.2.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Operator Overloading Fundamentals
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Road Map Introduction to object oriented programming. Classes
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
Lecture 12 Destructors “Absolute C++” Chapters 10.3, 15.2.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Pointers “Absolute C++” Section 10.1
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
Lecture 10 Inheritance “Absolute C++” Chapter 14.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Defining New Types Lecture 21 Hartmut Kaiser
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
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+
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
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.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Overloading operators C++ incorporates the option to use standard operators to perform operations with.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
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.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Operator Overloading.
Operator Overloading Introduction
Yan Shi CS/SE 2630 Lecture Notes
Programming with ANSI C ++
User-Written Functions
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
CS212: Object Oriented Analysis and Design
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
Operator overloading Dr. Bhargavi Goswami
Classes and Objects.
CISC/CMPE320 - Prof. McLeod
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
COP 3330 Object-oriented Programming in C++
Submitted By : Veenu Saini Lecturer (IT)
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS 144 Advanced C++ Programming February 21 Class Meeting
Classes “Absolute C++” Chapter 6
Lecture 3 More on Flow Control, More on Functions,
Presentation transcript:

Lecture 5 Constructors Operator Overloads “Absolute C++” Chapters 7.1,8.1,8.2

Constructors--an Introduction There’s an inefficiency with the Course class we looked at last time. In order to “set up” the class with initial data I have to call the “setter” functions manually, like this: void main() { Course cs213; cs213.setInstructor(“DiNapoli”); cs213.setStudentCount(45); cs213.setCourseName(“COM S 213”); // rest of program here }

Constructors--an Introduction I could set up an “init” member function that takes three arguments class Course { public: // These can be seen outside the class // init function void init(string argName,string argInstructor,int size); // Define member functions string getCourseName(); string getInstructor(); int getStudentCount(); void setCourseName(string theName); …

Constructors--an Introduction And define it like this: void Course:: init(string argName,string argInstructor,int size) { name = argName; instructor = argInstructor; numStudents = size; }

Constructors--an Introduction Then, whenever I needed to initialize a new instance of a “Course”, I could just use the “init” function: void main() { Course cs213; cs213.init(“COM S 213”,”DiNapoli”,45); // rest of program here }

Constructors--an Introduction In this “init” member function we can do things like: zero out member variables (provide initial values) allocate dynamic space C++ has a built in mechanism to doing this type of work. It is called a constructor. A constructor is a special member function which is always called immediately after space is allocated for the class instance in question. The member function name of the constructor is required to be the same name as the class. So, if we had a class named Calculator, we would define the constructor as follows:

Constructors class Calculator { public: Calculator(); // Declare the constructor bool calculate(char op,float arg1,float arg2,float &result); int getOperationsCount() { return opCount; } private: int opCount; }; // Here’s the constructor definition Calculator::Calculator() { opCount = 0; }

Simple Constructors Notice a couple of things: The constructor is declared in a public section Has the exact same name as the class itself There is no return type. Constructors cannot return a value! There are no arguments (parameters) A simple constructor has no parameters class Calculator { public: Calculator(); // Declare the constructor bool calculate(char op,float arg1,float arg2,float &result); int getOperationsCount() { return opCount; } private: int opCount; };

Simple Constructors Notice a couple of things: The constructor is defined the same way as any other member function Except, there is no return type Inside the constructor we can perform necessary initializations. When does a Constructor get called? A constructor gets called when the object is created. Whether the object is created statically (local variable) or dynamically (with the new operator) You do not need to explicitly call the constructor yourself. Let’s see an example... Calculator::Calculator() { opCount = 0; }

Demonstration #1 A Simple Constructor

Constructors with Arguments You may define constructors which take arguments as well. Consider a simple Course class similar to the one we used earlier class Course { public: Course(string theCourseName,string theInstructor, int classSize); private: string courseName; string instructor; int size; }; Notice how there is no “init” member function...

Constructors with Arguments We would define the Constructor as follows: Course::Course(string theCourseName,string theInstructor, int classSize) { courseName = theCourseName; instructor = theInstructor; size = classSize; } This saves us having to define a separate “init” member function More importantly, this will be called automatically! But if a constructor takes arguments, how do we pass them?

Constructors with Arguments There are two ways to call a constructor with arguments: We’ll cover the second way when we go cover pointers int main() { Course cs213(“COM S 213”,”Ron DiNapoli”,45); // Rest of program here } Again, this saves us having to write a separate “init” function But can you have a simple constructor declared as well? What happens if you do the following...

Overloaded Constructors Can you really have two member functions with the same name but different arguments? Yes, you can. It is called Overloading. The linker will make sure the right version gets called. class Course { public: Course(); // Simple Constructor Course(string theCourseName,string theInstructor, int classSize); // Constructor with arguments private: string courseName; string instructor; int size; };

Overloaded Constructors If a Course object is created with no arguments specified, the simple constructor is called... Course::Course() { courseName = “”; instructor = “”; size = 0; } Course::Course(string theCourseName,string theInstructor, int classSize) { courseName = theCourseName; instructor = theInstructor; size = classSize; }

Demonstration #2 Overloaded Constructors

A Simple Number Class class Number { public: Number(); Number(int initValue); void setBase(int); int getBase(); string printValue(); void setValue(int); int getValue(); private: long theValue; int base; }; For today’s lecture, we’ll play with the following Number class

Demonstration #3 A Simple Number Class

Inline Functions inline int performAddition(int x, int y) { return x+y; } Any function declaration may have the optional inline keyword A function designated as inline function will have the following behavior: Wherever this function is called the compiler has the option of replacing the call with the body of the actual function. This is, in theory, a way for programmers to optimize code themselves. The compiler may not listen to you: Recursive functions Very complex functions This is how you designate a function as being an “inline” function:

Operator Overloading In addition to overloading functions, you can also overload operators. The following operators may be overloaded: Unary Operators: ~ ! - + & * new new[] delete delete[] Binary Operators: -> * / % + - > >= == != & ^ | && || Assignment Operators: = *= /= %= += -= >= &= |= ^= You cannot alter precedence, only extend the definition as they apply to the particular class you are overloading them from.

Unary Operator Overloading (cont) Just for fun, let’s overload the unary ~ to mean string representation of Number, and + to mean integer value. To overload, we use the following definition: string Number::operator~() { return getValueStr(); } int Number::operator+() { return getValue(); } Let’s check it out...

Demonstration #4 Unary Operator Overloads

Binary Operator Overloading I can see it now, you’re all thinking “COOL, what else can we overload”. OK, ok, you don’t have to twist my arm. How about overloading the binary + to do addition? inline Number operator+(Number &num1, Number &num2) { // This is somewhat cheating. Let’s retrieve the // integer values, add them, then stuff them back // into a “Number” which we return Number temp( (+num1) + (+num2) ); return temp; } But why inline? Any why is this defined globally?

Binary Operator Overloading (cont) We need to define this stuff globally to avoid confusion over which argument is the actual instance of the class we’ve defined the operator in. The inline is necessary to allow us to place this in the header file without causing multiple definition errors. Now, I can use this overloaded operator as follows: int main() { Number n1(5); Number n2(6); Number n3; n3 = n1 + n2; cout << “Result is: “ << +n3; }

Demonstration #5 Binary Operator Overload

Overloading << inline ostream& operator<<(ostream &os,Number &aNum) { os << ~aNum; return os; } As with most binary operators, << must be overloaded globally. It takes an output stream reference ( ostream & ) as first argument. It takes a reference to whatever type you wish to overload the operator for as the second argument You need to return an ostream reference ( ostream & ) which is usually going to be the first parameter. Allows chaining, such as cout << num1 << “, “ << num2 ;

Overloading >> Overloading the >> operator is a little trickier because you either need to use >> again to actually get input OR you can use lower level routines to access the character stream directly. For this simple definition of operator>>, the easier method works. We’ll cover some cases later in the semester where you need to drop down to the lower level method. inline istream& operator>>(istream &is,Number &aNum) { int value; is >> value; aNum.setValue(value); return is; }

Consequences of Overloading Globally Whenever we overload globally instead of in the context of a particular class, the overload is implemented “outside of” that class. Private members are inaccessible Before you get tempted to make more member variables public to get around this, C++ has a mechanism to make exceptions to the “private” designation. It’s called a “friend” function class Number { public: friend ostream& operator<<(ostream &os,Number &aNum); friend istream& operator>>(istream &is,Number &aNum); friend int operator+ (const Number &n1,const Number &n2); // rest of definition here…

Demonstration #6 Overloaded >

Lecture 5 Final Thoughts…