Lecture 22: OO Languages: Smalltalk & C++ Smalltalk Class Commands

Total Page:16

File Type:pdf, Size:1020Kb

Lecture 22: OO Languages: Smalltalk & C++ Smalltalk Class Commands Smalltalk class class name Point super class Object Lecture 22: OO Languages: class var instance var x y Smalltalk & C++ class messages and methods !...names and code for methods..." CSC 131 instance messages and methods moveDx: dx Dy: dy || Spring, 2019 x <- dx+x y <- dy + y x Kim Bruce ^ x ... Commands Run-time representations Point class x • Loops example: superclass y 1 to:10 do:[:i| Point object Transcript show: (i asString). template ]. methods • Conditional class - (x>0) ifTrue:[ x:=x+1. ] ifFalse:[ x:=0 ]. Method dictionary - true and false are special values like x 2 code lambda calculus encodings newX:Y: ... code y 3 move code Dynamic Method Invocation Key ideas of Smalltalk • Everything is an object • Start with object’s class and search up superclasses. • Information hiding - instance variables protected. • When call method inside, start search from self again. • Dynamic typing, so subtyping determined by whether can masquerade -- “message not • Most other OO languages do not implement dmi in understood” this way -- too inefficient! • Inheritance distinct from subtyping removeFirst, removeLast, removeFirst:, and removeLast: defined for Intervals. 6 Interfaces Versus Inheritance removeFirst, removeLast, removeAtIndex: Figure 5 shows the Smalltalk inheritance hierar- and removeAllSuchThat: defined for LinkedList chy (in bold) superimposed on the protocol hierarchy after: and before: moved to SequenceableCol- of Figure 4 (dotted lines). This is a concrete illustra- lection tion of the difference, even at a syntactic level, be- addFirst:, addLast:, add:before:, add:after:, tween inheritance and conformance [CHC90, Syn- addAllFirst:, addAllLast:, and add:beforeIndex: der86]. There are two cases where the hierarchy and canceled from SortedCollection. protocol hierarchies are in direct conflict: Dictionary and SortedCollection. Dictionary inherits from Set 5.2 Extending the Analysis but its protocol does not conform to Set’s. This is The process for analyzing class libraries can be because DictionarySmalltalk cancels several of Set’s methods. applied to other parts of the Smalltalk. One area that SortedCollection has a similar pattern of inheritance would benefit from examination is the stream classes. without conformance. These classes are conceptually similar to collections, Collection but are implemented in an entirely different part of the class system. Indexed A Stream is a destination or source of values. Collection Streams are part of the collection classes but are not well integrated with the other collections. This sec- Set Updatable tion discusses how they could be unified with other Collection collections ReadStream Mapped Dictionary Sequenceable Extensible C++ Collection Collection Representation R : V* Collection Bag isEmpty ρ = ( #R = 0 ) Poppable Collection #R > 0 next R' = ρ•R Array Interval Internally #R > 0 peek ρ = R[1] Removable The next method has the same specification as Collection the removeFirst method in OrderedCollection. The String fact that it removes the first element instead of the last Ordered Sorted is merely an artifact of the specification; it is not vis- Collection Collection & ible to the client. Similarly, peek corresponds to the LinkedList first method. Figure 5: Interfaces versus Inheritance WriteStream Representation R : V* Another significant deviation centers around Se- quenceableCollection, which has inheritors nextPut: x R = R'•x (subclasses) with various combinations of protocols contents ρ = R unrelated to SequenceableCollection. Some of the subclasses (Array and String) are Updatable but not The method nextPut: has the same specification Extensible, since they support at:put:. Other sub- as addLast: in OrderedCollection, but is indepen- classes (LinkedList and SortedCollection) are Ex- dent of the actual ordering used. Renaming the next- tensible but not Updatable, since they support add:. Put: to be add: allows for more polymorphism; A final one (OrderedCollection) is both Extensible WriteStream then conforms to ExtensibleCollec- and Updatable. The abstract classes in Smalltalk tion. act as mixins for methods that depend upon a key subclass responsibility method; to express this struc- C++ Design Goals Additions to C • Data abstraction & OO features • type bool • Better static type checking • reference types & call by reference • Backwards compatibility w/ C • user-defined overloading • Efficiency: If you do not use a feature, you • templates should not pay for it • exceptions • Explicitly hybrid language -- C w/abstraction • public or private inheritance Problems Casts & Conversions • Implicit conversions: • Confusing casts and conversions - from short to int • Objects allocated on stack - class B { public: B (A a) {} }; A a; B b = a; - what happens w/subtyping? truncation! • Explicit conversions: - C c; D* d; d = (D*) &c; d -> DonlyMeth(); • Overloading methods -- see earlier examples! • Try to avoid problems by using new casts: - static_cast, dynamic_cast, reinterp_cast, const_cast • Multiple inheritance (later) - dynamic_cast checks using run-time type info (RTTI) - reinterp_cast trusts Objects on stack OO Features in C++ • Visibility • Doesn’t interact well with subtyping. - Public, protected, private - Friends ... • Point p; // allocates point on stack • Virtual vs. nonvirtual functions • ColorPoint cp(3,4,blue); - don’t pay the price of dynamic method invocation • p = cp; // slices and converts to Point • Implemented via vtable • Call by value has similar problems - no search necessary • What about reference parameters to methods? - static typing makes efficient rep possible - efficient iff subtype fom inheritance! VTable for Virtual methods C++ vs Smalltalk implementation Point object Point vtable vptr getX code x 2 ... code translate code • No search in C++ since offset for given method y 3 same in base and derived classes ColorPoint object • Smalltalk has no type declaration ColorPoint vtable vptr - value not known to be subtype of declared type getX no idea where method is located x 2 ... - y 3 translate color red getColor code Abstract classes Multiple Inheritance • Have at least one method undefined • Appealing: TA derived from Student and Teacher. • “Pure” leaves all undefined • Added to C++ and Smalltalk. In Eiffel from • Can’t construct, but can inherit from beginning. • Derived subclasses can be used as subtypes of • Problems conceptually and with abstract base class. implementation MI in C++ Representing MI class S {...} TA as S vtable class T{...} ps,pta TA object class TA: public S, public T code vptr {...} code S data pt ... TA as T vtable vptr TA* pta = new TA(); code S * ps = pta; T data ... code T * pt = pta; TA data code What if T and TA both define virtual f? T methods expect inst vbles starting at pt How get access to instance vbles fom S? Conceptual Problems w/ MI Java Solution A • Most multiple inheritance in C++ involves pure base classes. B C • Java: Single inheritance, but can implement multiple interfaces. D • Avoids problems. Diamond Inheritance: Suppose A has virtual f • Traits (e.g., in Scala) are modern alternative. and B and C override it. Which version is inherited in D? C++ Summary C++ Humor C++: Hard to learn and built to stay that way. • One of most complicated languages ever • Java is, in many ways, C++--. - design by accretion • • How C++ is like teenage sex: • Meets design goals but very hard to get right 1. It is on everyone's mind all the time. Everyone talks about it all the time. “C makes it easy to shoot yourself in the foot. In C++ 2. - Everyone thinks everyone else is doing it. it's harder to shoot yourself in the foot, but when you 3. do, you blow off your whole leg.” -- Stroustrup 4.Almost no one is really doing it. 5. The few who are doing it are: • Memory management is big problem A. Doing it poorly. • Most programmers learn a subset. B. Sure it will be better next time. C. Not practicing it safely. Java Design Goals • Portability across platforms • Reliability Java • Safety (no viruses!) • Dynamic Linking • Multithreaded execution • Simplicity and Familiarity • Efficiency Java Exceptions & Subtyping • Original implementations slow - Compiled to JVML and then interpreted - Now JIT • All non-Runtime exceptions must be caught or - Garbage collection declared in “throws” clauses Safety - 3 levels: • - void method readFiles() throws IOException {...} - Strongly typed Suppose m throws NewException. - JVML bytecode also checked before execution • - Run-time checks for array bounds, etc. • What are restrictions on throwing exceptions if m overridden in subclass? Masquerade! • Other safety features: - No pointer arithmetic, unchecked type casts, etc. - Super constructor called at beginning of constructor Simplify from C++ Interfaces • Purely OO language (except for primitives) • All objects accessed through pointers • Originally introduced to replace multiple inheritance - reference semantics • No multiple inheritance -- trade for interfaces • Allows pure use of subtype polymorphism w/ out confusing with implementation reuse. • No operator overloading • Slower access to methods as method order not • No manual memory management guaranteed • No automatic or unchecked conversions Encapsulation Problems w/Packages • Generally tied to directory structure. • Classes & interfaces can belong to packages: package MyPackage; • Anyone can add to package and get privileged access public class C ... • If no explicit package then in “default” package • All classes/interfaces w/out named package in default package (so all have access to each • public, protected, private, “package” visibility other!) • Class-based privacy (not object-based): • No explicit interface for package - If method has parameter of same type then get access Abstraction barriers not possible for interfaces. to privates of parameter • Discourages use of interfaces for classes..
Recommended publications
  • Function Overloading in C Sharp with Example
    Function Overloading In C Sharp With Example syncarpyGraig plied if Frederichtracklessly. is Burtonculinary disappear or blunder invidiously irrespective. while exemplifiable Tristan alters joyously or raked pardi. Ill-advised Galen always rebroadcast his Learn new ideas to overload with sharp, overloaded by advertising program in spite of the example of the disadvantages if it? Follow me at medium. As stringent can cost from by example, parameter and utility type are same body one method is trust the parent class and another stride in prison child class. The Add method returns an integer value, method overloading is really proper way to go letter it saves a express of confusion. The method takes two parameters myInteger and myUnsignedInt and returns their sum. The implementation is not shown here. Polymorphism In C With contingency Time Example Programming. But bury all consumers support Optional Parameters. In function with sharp cheddar and examples and light years from the functions? You can achieve method overriding using inheritance. It is baked macaroni in function c sharp cheddar and data. Suited for everyday polygon hassle. The functions with the same. Thanks for awesome post. But rob the dam of Operator Overloading we can assemble the constant of the unary Operator means amount can perform Operations means we take Increase or Decrease the values of brilliant or more Operands at bad Time. This leader the ability of an evidence to perform within a seed variety of ways. Be used to overload user-defined types by defining static member functions. Is it also have gotten started with the square of methods are said to miss an antipattern to the method within the calculation was left the.
    [Show full text]
  • Chapter 7 Expressions and Assignment Statements
    Chapter 7 Expressions and Assignment Statements Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment Statements Mixed-Mode Assignment Chapter 7 Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language. To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation. Essence of imperative languages is dominant role of assignment statements. Arithmetic Expressions Their evaluation was one of the motivations for the development of the first programming languages. Most of the characteristics of arithmetic expressions in programming languages were inherited from conventions that had evolved in math. Arithmetic expressions consist of operators, operands, parentheses, and function calls. The operators can be unary, or binary. C-based languages include a ternary operator, which has three operands (conditional expression). The purpose of an arithmetic expression is to specify an arithmetic computation. An implementation of such a computation must cause two actions: o Fetching the operands from memory o Executing the arithmetic operations on those operands. Design issues for arithmetic expressions: 1. What are the operator precedence rules? 2. What are the operator associativity rules? 3. What is the order of operand evaluation? 4. Are there restrictions on operand evaluation side effects? 5. Does the language allow user-defined operator overloading? 6. What mode mixing is allowed in expressions? Operator Evaluation Order 1. Precedence The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated (“adjacent” means they are separated by at most one operand).
    [Show full text]
  • MANNING Greenwich (74° W
    Object Oriented Perl Object Oriented Perl DAMIAN CONWAY MANNING Greenwich (74° w. long.) For electronic browsing and ordering of this and other Manning books, visit http://www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. 32 Lafayette Place Fax: (203) 661-9018 Greenwich, CT 06830 email: [email protected] ©2000 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Library of Congress Cataloging-in-Publication Data Conway, Damian, 1964- Object oriented Perl / Damian Conway. p. cm. includes bibliographical references. ISBN 1-884777-79-1 (alk. paper) 1. Object-oriented programming (Computer science) 2. Perl (Computer program language) I. Title. QA76.64.C639 1999 005.13'3--dc21 99-27793 CIP Manning Publications Co. Copyeditor: Adrianne Harun 32 Lafayette
    [Show full text]
  • Operator Overloading ______
    Chapter 10: Operator Overloading _________________________________________________________________________________________________________ Consider the following C++ code snippet: vector<string> myVector(kNumStrings); for(vector<string>::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) *itr += "Now longer!"; Here, we create a vector<string> of a certain size, then iterate over it concatenating “Now longer!” to each of the strings. Code like this is ubiquitous in C++, and initially does not appear all that exciting. However, let's take a closer look at how this code is structured. First, let's look at exactly what operations we're performing on the iterator: vector<string> myVector(kNumStrings); for(vector<string>::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) *itr += "Now longer!"; In this simple piece of code, we're comparing the iterator against myVector.end() using the != operator, incrementing the iterator with the ++ operator, and dereferencing the iterator with the * operator. At a high level, this doesn't seem all that out of the ordinary, since STL iterators are designed to look like regular pointers and these operators are all well-defined on pointers. But the key thing to notice is that STL iterators aren't pointers, they're objects, and !=, *, and ++ aren't normally defined on objects. We can't write code like ++myVector or *myMap = 137, so why can these operations be applied to vector<string>::iterator? Similarly, notice how we're concatenating the string “Now longer!” onto the end of the string: vector<string> myVector(kNumStrings); for(vector<string>::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) *itr += "Now longer!"; Despite the fact that string is an object, somehow C++ “knows” what it means to apply += to strings.
    [Show full text]
  • The Future: the Story of Squeak, a Practical Smalltalk Written in Itself
    Back to the future: the story of Squeak, a practical Smalltalk written in itself Dan Ingalls, Ted Kaehler, John Maloney, Scott Wallace, and Alan Kay [Also published in OOPSLA ’97: Proc. of the 12th ACM SIGPLAN Conference on Object-oriented Programming, 1997, pp. 318-326.] VPRI Technical Report TR-1997-001 Viewpoints Research Institute, 1209 Grand Central Avenue, Glendale, CA 91201 t: (818) 332-3001 f: (818) 244-9761 Back to the Future The Story of Squeak, A Practical Smalltalk Written in Itself by Dan Ingalls Ted Kaehler John Maloney Scott Wallace Alan Kay at Apple Computer while doing this work, now at Walt Disney Imagineering 1401 Flower Street P.O. Box 25020 Glendale, CA 91221 [email protected] Abstract Squeak is an open, highly-portable Smalltalk implementation whose virtual machine is written entirely in Smalltalk, making it easy to debug, analyze, and change. To achieve practical performance, a translator produces an equivalent C program whose performance is comparable to commercial Smalltalks. Other noteworthy aspects of Squeak include: a compact object format that typically requires only a single word of overhead per object; a simple yet efficient incremental garbage collector for 32-bit direct pointers; efficient bulk- mutation of objects; extensions of BitBlt to handle color of any depth and anti-aliased image rotation and scaling; and real-time sound and music synthesis written entirely in Smalltalk. Overview Squeak is a modern implementation of Smalltalk-80 that is available for free via the Internet, at http://www.research.apple.com/research/proj/learning_concepts/squeak/ and other sites. It includes platform-independent support for color, sound, and image processing.
    [Show full text]
  • Dynamic Operator Overloading in a Statically Typed Language Olivier L
    Dynamic Operator Overloading in a Statically Typed Language Olivier L. Clerc and Felix O. Friedrich Computer Systems Institute, ETH Z¨urich, Switzerland [email protected], [email protected] October 31, 2011 Abstract Dynamic operator overloading provides a means to declare operators that are dispatched according to the runtime types of the operands. It allows to formulate abstract algorithms operating on user-defined data types using an algebraic notation, as it is typically found in mathematical languages. We present the design and implementation of a dynamic operator over- loading mechanism in a statically-typed object-oriented programming lan- guage. Our approach allows operator declarations to be loaded dynam- ically into a running system, at any time. We provide semantical rules that not only ensure compile-time type safety, but also facilitate the im- plementation. The spatial requirements of our approach scale well with a large number of types, because we use an adaptive runtime system that only stores dispatch information for type combinations that were encoun- tered previously at runtime. On average, dispatching can be performed in constant time. 1 Introduction Almost all programming languages have a built-in set of operators, such as +, -, * or /, that perform primitive arithmetic operations on basic data types. Operator overloading is a feature that allows the programmer to redefine the semantics of such operators in the context of custom data types. For that purpose, a set of operator implementations distinguished by their signatures has to be declared. Accordingly, each operator call on one or more custom-typed arguments will be dispatched to one of the implementations whose signature matches the operator's name and actual operand types.
    [Show full text]
  • Smalltalk's Influence on Modern Programming
    1 Smalltalk’s Influence on Modern Programming Smalltalk’s Influence on Modern Programming Matt Savona. February 1 st , 2008. In September 1972 at Xerox PARC, Alan Kay, Ted Kaeher and Dan Ingalls were discussing programming languages in the hallway of their office building. Ted and Dan had begun to consider how large a language had to be to have “great power.” Alan took a different approach, and “asserted that you could define the "most powerful language in the world" in "a page of code."” Ted and Dan replied, “Put up or shut up” (Kay). And with that, the bet to develop the most powerful language was on. Alan arrived at PARC every morning at 4am for two weeks, and devoted his time from 4am to 8am to the development of the language. That language was Smalltalk. Kay had “originally made the boast because McCarthy's self-describing LISP interpreter was written in itself. It was about "a page", and as far as power goes, LISP was the whole nine- yards for functional languages.” He was sure that he could “do the same for object-oriented languages” and still have a reasonable syntax. By the eighth morning, Kay had a version of Smalltalk developed where “symbols were byte-coded and the receiving of return-values from a send was symmetric” (Kay). Several days later, Dan Ingalls had coded Kay’s scheme in BASIC, added a “token scanner”, “list maker” and many other features. “Over the next ten years he made at least 80 major releases of various flavors of Smalltalk” (Kay).
    [Show full text]
  • Cross-Language Interop Poster
    Low Cognitive Overhead Bridging "Interoperability isn't just a technical problem, it's also a user interface problem. We have to make it easy to call between languages, so that users can The demo shown at FOSDEM always pick the most appropriate tool for the job at hand." example [ this year showed fully dynamic "This shows how to call a C function from Smalltalk" development spanning C objc_setAssociatedObject: { Objective-C and Smalltalk. The self. 42. developer can inspect the ’fishes’. existing class hierarchy and C enumValue: OBJC_ASSOCIATION_ASSIGN }. the code for any methods "Note how C enumerations can be accessed. When encountering this construct, the Pragmatic Smalltalk compiler will generate exactly the same code as an implemented in Smalltalk. It Objective-C compiler would for this line: is also possible to add, modify, objc_setAssociatedObject(self, 42, @"fishes", OBJC_ASSOCIATION_ASSIGN); or replace methods, add It will get the types for the function by parsing the header and automatically map Smalltalk types to C and Objective-C types. The instance variables and classes Easy Development programmer doesn't need to write any bridging or foreign function interface at run time. Invoking a code." nonexistent class or method (C objc_getAssociatedObject: {self . 42 }) log. ] pops up a dialog asking the user to implement it, all from within a running app. The final version is statically compiled, with no explicit user Cross-Language Interoperability for intervention required. Fast, Easy, and Maintainable Code David Chisnall The World Today: But I wanted to use the But libfoo is C, libbar Frobnicator framework, and it's I have a great idea is C++, and I want to only for Java.
    [Show full text]
  • A Summary of Operator Overloading Basic Idea
    A Summary of Operator Overloading David Kieras, EECS Dept., Univ. of Michigan Prepared for EECS 381 8/27/2013 Basic Idea You overload an operator in C++ by defining a function for the operator. Every operator in the language has a corresponding function with a name that is based on the operator. You define a function of this name that has at least one parameter of the class type, and returns a value of whatever type that you want. Because functions can have the same name if they have different signatures, the compiler will apply the correct operator function depending on the types in the call of it. Rule #1. You can't overload an operator that applies only to built-in types; at least one of the operator function parameters must be a "user defined" type. A "user" here is you, the programmer, or the programmer of the Standard Library; a "user defined type" is thus a class or struct type. This means you can't overload operator+ to redefine what it means to add two integers. Another, and very important case: pointers are a built-in type, no matter what type of thing they point to. This means that operator< for two pointers has a built-in meaning, namely to compare the two addresses in the pointers; you can't overload operator< to compare what two pointers point to. The Standard Library helps you work around this limitation. You define operator functions differently depending on whether the operator function is a member of your own type's class, or is a non-member function.
    [Show full text]
  • Smalltalk Language Mapping Specification
    Smalltalk Language Mapping Specification New Edition: June 1999 Copyright 1995, 1996 BNR Europe Ltd. Copyright 1998, Borland International Copyright 1991, 1992, 1995, 1996 Digital Equipment Corporation Copyright 1995, 1996 Expersoft Corporation Copyright 1996, 1997 FUJITSU LIMITED Copyright 1996 Genesis Development Corporation Copyright 1989, 1990, 1991, 1992, 1995, 1996 Hewlett-Packard Company Copyright 1991, 1992, 1995, 1996 HyperDesk Corporation Copyright 1998 Inprise Corporation Copyright 1996, 1997 International Business Machines Corporation Copyright 1995, 1996 ICL, plc Copyright 1995, 1996 IONA Technologies, Ltd. Copyright 1996, 1997 Micro Focus Limited Copyright 1991, 1992, 1995, 1996 NCR Corporation Copyright 1995, 1996 Novell USG Copyright 1991,1992, 1995, 1996 by Object Design, Inc. Copyright 1991, 1992, 1995, 1996 Object Management Group, Inc. Copyright 1996 Siemens Nixdorf Informationssysteme AG Copyright 1991, 1992, 1995, 1996 Sun Microsystems, Inc. Copyright 1995, 1996 SunSoft, Inc. Copyright 1996 Sybase, Inc. Copyright 1998 Telefónica Investigación y Desarrollo S.A. Unipersonal Copyright 1996 Visual Edge Software, Ltd. The companies listed above have granted to the Object Management Group, Inc. (OMG) a nonexclusive, royalty-free, paid up, worldwide license to copy and distribute this document and to modify this document and distribute copies of the modified ver- sion. Each of the copyright holders listed above has agreed that no person shall be deemed to have infringed the copyright in the included material of any such copyright holder by reason of having used the specification set forth herein or having con- formed any computer software to the specification. PATENT The attention of adopters is directed to the possibility that compliance with or adoption of OMG specifications may require use of an invention covered by patent rights.
    [Show full text]
  • Operator Overloading
    CSE 230 Intermediate Programming in C and C++ Operator Overloading Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Ref. Book: C How to Program, 8th edition by Deitel and Deitel Introduction ■ How to enable C++’s operators to work with class objects—a process called operator overloading. ■ The jobs performed by overloaded operators also can be performed by explicit function calls, but operator notation is often more natural. Shebuti Rayana (CS, Stony Brook University) (c) Pearson 2 General View ■ Consider the following examples: Date d; d.increment(); Bag b; cout << b.getData(i); b.setData(i, value); Matrix x, y, z; x.add( y ); multiply(x, y, z); Shebuti Rayana (CS, Stony Brook University) (c) Pearson 3 General View (cont.) ■ How do you prefer the replacements below? Date d; d.increment(); d++; Bag b; cout << b.getData(i); cout << b[i]; b.setData(i,value); b[i] = value; Matrix x, y, z; x.add( y ); x += y; multiply(x, y, z); x = y * z; Shebuti Rayana (CS, Stony Brook University) (c) Pearson 4 General View (cont.) ■ Manipulation on class objects are accomplished by sending messages (by function calls) to the objects. ■ Function-call notation is cumbersome for certain kinds of classes, especially mathematical classes. ■ It would be nice to use C++’s rich set of built-in operators to specify object manipulation. ■ For example, operator << (or >>, +, -, etc.) has several purposes as the stream-insertion and bitwise left-shift. ■ Overloaded operators perform operation depending on their context and set of operands. Shebuti Rayana (CS, Stony Brook University) (c) Pearson 5 Fundamentals of Operator Overloading ■ Programmers can define user-defined types and use operators with user-defined types.
    [Show full text]
  • Dynamic Object-Oriented Programming with Smalltalk
    Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz Autumn Semester 2009 LECTURE TITLE What is surprising about Smalltalk > Everything is an object > Everything happens by sending messages > All the source code is there all the time > You can't lose code > You can change everything > You can change things without restarting the system > The Debugger is your Friend © Oscar Nierstrasz 2 ST — Introduction Why Smalltalk? > Pure object-oriented language and environment — “Everything is an object” > Origin of many innovations in OO development — RDD, IDE, MVC, XUnit … > Improves on many of its successors — Fully interactive and dynamic © Oscar Nierstrasz 1.3 ST — Introduction What is Smalltalk? > Pure OO language — Single inheritance — Dynamically typed > Language and environment — Guiding principle: “Everything is an Object” — Class browser, debugger, inspector, … — Mature class library and tools > Virtual machine — Objects exist in a persistent image [+ changes] — Incremental compilation © Oscar Nierstrasz 1.4 ST — Introduction Smalltalk vs. C++ vs. Java Smalltalk C++ Java Object model Pure Hybrid Hybrid Garbage collection Automatic Manual Automatic Inheritance Single Multiple Single Types Dynamic Static Static Reflection Fully reflective Introspection Introspection Semaphores, Some libraries Monitors Concurrency Monitors Categories, Namespaces Packages Modules namespaces © Oscar Nierstrasz 1.5 ST — Introduction Smalltalk: a State of Mind > Small and uniform language — Syntax fits on one sheet of paper >
    [Show full text]