Overview of Previous Lesson(s) Over View  Operator Overloading:  Operator overloading is a very important capability, it enables to make standard C++

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Operator Overloading in C++
Basic Elements of C++ Chapter 2.
From C++ to C#. Web programming The course is on web programming using ASP.Net and C# The course is on web programming using ASP.Net and C# ASP.Net is.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Operator Overloading and Type Conversions
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Ryan Chu. Arithmetic Expressions Arithmetic expressions consist of operators, operands, parentheses, and function calls. The purpose is to specify an.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
1 Chapter 8 Destructor & Operator Overloading. 2 Destructor  A destructor is a function that is called when an object is no longer required. A constructor.
Overview of Previous Lesson(s) Over View .NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows.  It.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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:
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Controlling Program Flow with Decision Structures.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
Overview of Previous Lesson(s) Over View VP is the methodology in which development allows the user to grab and use the desired tools like menus, buttons,
Overview of Previous Lesson(s) Over View 3  CLR Programming  Common Language Runtime (CLR) is a programming, that manages the execution of programs,
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
Memory Management.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Operator Overloading BCA Sem III K.I.R.A.S.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
We’re slowly working our way towards classes and objects
Operator overloading Dr. Bhargavi Goswami
Chapter 6 Control Statements: Part 2
Stacks.
CISC/CMPE320 - Prof. McLeod
Data Structures and Algorithms Introduction to Pointers
Java Programming Language
Chapter 8 (Part 2) Destructor & Operator Overloading (P.331)
送孟浩然之廣陵 ~李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧空盡, 惟見長江天際流。.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Overview of Previous Lesson(s)

Over View  Operator Overloading:  Operator overloading is a very important capability, it enables to make standard C++ operators, such as +, -, *, and so on, work with objects of user defined data types.  Following operators can’t be overloaded: 3

Over View..  Class Template  A class template is not a class, but a sort of recipe for a class that will be used by the compiler to generate the code for a class. 4

Over View…  A pointer is a variable that stores the address of another variable of a particular type. long *pnum;//convention in C++  For getting the address & operator is used.  This is a unary operator that obtains the address of a variable.  It ’ s also called the reference operator. long number = 200; long* pnumber; pnumber = &number; 5

Over View… 6  Operator & can be used to obtain the address of any variable, but you need a pointer of the appropriate type to store it.

Over View…  Enumerations: enum class Suit{Clubs, Diamonds, Hearts, Spades};  This defines an enumeration type, Suit, and variables of type Suit can be assigned only one of the values defined by the enumeration, Hearts, Clubs, Diamonds, or Spades. Suit suit = Suit::Clubs;  This statement assigns the value Clubs from the Suit enumeration to the variable with the name suit. 7

Over View…  Reading Key Presses.  AS we see earlier that Console::ReadKey(true); is used to store the result in the variable keypress, which is of type ConsoleKeyInfo.  Lets have a look into an example which uses Readkey() and do while loop in CLR programming.  Task:  Continue to Press a key until Escape key is pressed. 8

9

Contents  Using Classes  Defining a Problem  Implementing the CBox class  Comparing CBox Objects  Combining CBox Objects  Analyzing CBox Objects  CLR Programming  Nested If Statements  Reading Key Presses  For each Loop  Tracking Handles 10

Using Classes  Until now we have touched on most of the basic aspects of defining a native C++ class.  So now we should look at how a class might be used to solve a problem.  The problem has to be simple so that we can try to focus on the complete solution so we ’ ll consider problems in which we can use an extended version of the CBox class. 11

Defining a Problem  The principal function of a box is to contain objects of one kind or another, so, in one word, the problem is packaging.  Basic operations that we might want to provide in the CBox class include:  Calculate the volume of a Cbox. (Already done)  Compare the volumes of two CBox objects to determine which is the larger. (Already done) 12

Defining a Problem..  Compare the volume of a CBox object with a specified value, and vice versa.  Add two CBox objects to produce a new CBox object that will contain both the original objects. Thus, the result will be at least the sum of the volumes, but may be larger.  Multiply a CBox object by an integer (and vice versa) to provide a new CBox object that will contain a specified number of the original objects.  This is effectively designing of a carton. 13

Defining a Problem...  Determine how many CBox objects of a given size can be packed in another CBox object of a given size.  This is effectively division, so you could implement this by overloading the / operator.  Determine the volume of space remaining in a CBox object after packing it with the maximum number of CBox objects of a given size. 14

Cbox Class  We need a bit change in our existing Cbox class to address all the problems: class CBox // Class definition at global scope { public: // Constructor definition explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0) { lv = lv < = 0 ? 1.0 : lv; // Ensure positive wv = wv < = 0 ? 1.0 : wv; // dimensions for hv = hv < = 0 ? 1.0 : hv; // the object m_Length = lv > wv ? lv : wv; // Ensure that m_Width = wv = width m_Height = hv; } 15

Cbox Class.. // Function to calculate the volume of a box double Volume() const {return m_Length*m_Width*m_Height;} // Function providing the length of a box double GetLength() const { return m_Length; } // Function providing the width of a box double GetWidth() const { return m_Width; } // Function providing the height of a box double GetHeight() const { return m_Height; } 16

Cbox Class.. private: double m_Length; // Length of a box in inches double m_Width; // Width of a box in inches double m_Height; // Height of a box in inches };  The constructor is now secure because any dimension that the user of the class tries to set to a negative number or zero will be set to 1 in the constructor. 17

Comparing Cbox Objects  We have to include support for the operators >, > =, ==, <, and < = so that they work with both operands as CBox objects, as well as between a CBox object and a value of type double.  We can implement these as ordinary global functions because they don’t need to be member functions.  They can be written as functions that compare the volumes of two CBox objects in terms of the functions that compare the volume of a CBox object with a double value, 18

Comparing Cbox Objects.. // Function for testing if a constant is > a CBox object bool operator > (const double & value, const CBox & aBox) {return value > aBox.Volume();} // Function for testing if a constant is < a CBox object bool operator < (const double & value, const CBox & aBox) {return value < aBox.Volume();} 19

Comparing Cbox Objects…  We can code the implementations of the same operators with the arguments reversed in terms of the two functions you have just defined: // Function for testing if CBox object is > a constant bool operator > (const CBox & aBox, const double & value) { return value < aBox; } // Function for testing if CBox object is < a constant bool operator < (const CBox & aBox, const double & value) { return value > aBox; } 20

Comparing Cbox Objects…  The operator==() functions are also very similar: // Function for testing if constant is == the volume of a CBox object bool operator==(const double & value, const CBox & aBox) { return value == aBox.Volume(); } // Function for testing if CBox object is == a constant bool operator==(const CBox & aBox, const double & value) { return value == aBox; } 21

Combining Cbox Objects  Now, the time comes for the question of overloading the operators +, *, /, and %. // Function adding two CBox objects CBox operator+(const CBox & aBox) const; { // New object has larger length & width, and sum of heights return CBox( m_Length > aBox.m_Length ? m_Length :aBox.m_Length, m_Width > aBox.m_Width ? m_Width : aBox.m_Width, m_Height + aBox.m_Height ); } 22

Addition Operation 23

Multiply Operation  It represents the process of creating a box to contain n boxes, where n is the multiplier.  The simplest solution would be to take the m_Length and m_Width of the object to be packed and multiply the height by n to get the new CBox object.  You can make it a little cleverer by checking whether or not the multiplier is even and, if it is, stack the boxes side by side by doubling the m_Width value and only multiplying the m_Height value by half of n. 24

Multiply Operation.. 25

Multiply Operation… 26  As a member function with the left operand as a CBox object: // CBox multiply operator this*n CBox operator*(int n) const { if(n % 2) return CBox(m_Length, m_Width, n*m_Height); // n odd else return CBox(m_Length, 2.0*m_Width, (n/2)*m_Height); // n even }  Here, you use the % operator to determine whether n is even or odd.  If n is odd, the value of n % 2 is 1 and the if statement is true.  If it is even, n % 2 is 0 and the statement is false.

Multiply Operation… 27  As a simple non-member function with the left operand as an int. // CBox multiply operator n*aBox CBox operator*(int n, const CBox & aBox) { return aBox*n; }  This version of the multiply operation simply reverses the order of the operands so as to use the previous version of the function directly.

Analyzing Cbox Objects  Division operation will determine how many CBox objects identical to that specified by the right operand can be contained in the CBox object specified by the left operand.  To keep it relatively simple, assume that all the CBox objects are packed the right way up, that is, with the height dimensions vertical. 28

Divide Operation.. 29

Divide Operation… 30 int operator/(const CBox & aBox) const { int tc1 = 0; // Temporary for number in horizontal plane this way int tc2 = 0; // Temporary for number in a plane that way tc1 = static_cast ((m_Length / aBox.m_Length))* static_cast ((m_Width / aBox.m_Width)); // and that way Return best fit tc2 = static_cast ((m_Length / aBox.m_Width))* static_cast ((m_Width / aBox.m_Length)); return static_cast ((m_Height/aBox.m_Height)*(tc1 > tc2 ? tc1 : tc2)); }

% Operation 31  The other analytical operator function, operator%(), for obtaining the free volume in a packed aBox is easier, because it uses the operator /, which is already defined.  It can be written as an an ordinary global function because the private members of the class are don’t need to be accessed. // Operator to return the free volume in a packed box double operator%(const CBox & aBox, const CBox & bBox) { return aBox.Volume() - ((aBox/bBox)*bBox.Volume()); }  The result is the volume of the big box, aBox, minus the volume of the bBox boxes that can be stored in it.

C++ / CLI Programming 32

For each loop  All the loop statements apply equally well to C++/CLI programs, and the C++/CLI language provides with the luxury of an additional kind of loop called the for each loop.  This loop also works with native C++ code in Visual C , although formally the for each loop is not part of the ISO/IEC standard C++ language.  The for each loop is specifically for iterating through all the objects in a particular kind of set of objects. 33

For each loop.. #include "stdafx.h" using namespace System; int main(array ^args) { int vowels(0), consonants(0); String^ proverb(L“When in Rome, do as the Romans."); for each(wchar_t ch in proverb) { if(Char::IsLetter(ch)) { ch = Char::ToLower(ch); // Convert to lowercase switch(ch) { case 'a': case 'e': case 'i': 34

For each loop… case 'o': case 'u': ++vowels; break; default: ++consonants; break; } Console::WriteLine(proverb); Console::WriteLine(L"The proverb contains {0} vowels and {1} consonants.", vowels, consonants); return 0; } 35

For each loop…  This loop counts the vowels and constants.  Lets check this … 36

Tracking Handles  A tracking handle has similarities to a native C++ pointer, but there are also some significant differences.  A tracking handle does store an address, which is automatically updated by the garbage collector if the object it references is moved during compaction of the heap.  Garbage Collector:  In C and C++, many objects require the programmer to allocate their resources once declared, before the objects can be safely used.  Releasing these resources back to the free memory pool once the object has been used is the responsibility of the programmer. 37

Garbage Collector  If resources are not released, the code is said to leak memory, as more and more resources are consumed needlessly.  On the other hand, if resources are released prematurely, loss of data, the corruption of other memory areas, and null pointer exceptions can occur.  The CLR garbage collector periodically checks the memory heap for any unreferenced objects, and releases the resources held by these objects. 38

Tracking Handles..  However, you cannot perform address arithmetic with a tracking handle as you can with a native pointer, and casting a tracking handle is not permitted.  For instance, the String class type is a reference class type, so variables that reference String objects must be tracking handles. 39

Creating Tracking Handles  A handle is specified for a type by placing the ^ symbol following the type name. String^ proverb;  This defines the variable proverb to be a tracking handle of type String^.  When a handle is declared it is automatically initialized with null, so it will not refer to anything.  To explicitly set a handle to null you use the keyword nullptr like this: proverb = nullptr; // Set handle to null 40

Creating Tracking Handles..  Of course, you can initialize a handle explicitly when you declare it.  Here ’ s another statement that defines a handle to a String object: String^ saying(L"I used to think I was indecisive but now I'm not so sure");  This statement creates a String object on the heap that contains the string between the parentheses.  Address of the new object is stored in saying.  Here ’ s how you could create a handle for a value type: int^ value(99);  This statement creates the handle value of type int^ ; the value it points to on the heap is initialized to

Thank You 42