CS11 Advanced C++ Fall Lecture 7
|
|
- Arline Austin
- 6 years ago
- Views:
Transcription
1 CS11 Advanced C++ Fall Lecture 7
2 Today s Topics Explicit casting in C++ mutable keyword and const Template specialization Template subclassing
3 Explicit Casts in C and C++ C has one explicit cast operator for everything Can convert between related types e.g. double to int Can cast pointers to different types e.g. void* to float*, or float* to char* Can cast pointers to int, and vice versa Can cast away const-ness Many unsafe or potentially unsafe scenarios! C++ provides four explicit casting operators Breaks down different kinds of casts into explicit operations Provides more type-safety checks at compile-time, run-time Easier for programmers to understand, too!
4 C++ Cast Operations const_cast Casts away const-ness static_cast Performs safe conversions between related types, using static type information dynamic_cast Uses runtime type information to safely cast down or across class hierarchies reinterpret_cast For all the dangerous stuff.
5 Removing const Constraints const_cast removes const constraints T const_cast<t>(const T value) Not for changing the type of value! Using const_cast to change types will not compile Examples: void update(specialwidget *psw); const SpecialWidget csw; update(&csw); // COMPILE ERROR update(const_cast<specialwidget*>(&csw)); // OK Widget *pw = new SpecialWidget(); update(const_cast<specialwidget*>(pw)); // COMPILE ERROR
6 Cached Values and const const_cast sometimes used when objects cache temporary values that are expensive to compute class Date {... string cache; bool cachevalid; void updatecachevals(); // sets cache value public:... string stringrep() const; }; stringrep() returns a string version of the date value Cache the result, as long as date value doesn t change
7 Cached Values and const (2) Implementation of stringrep() string Date::stringRep() const { if (!cachevalid) { // this is const, so cast to non-const Date* Date *mut = const_cast<date*>(this); mut->updatecachevals(); mut->cachevalid = true; } return cache; } this is const because the member function is const Must cast away const to update cached values!
8 Cached Values and const (3) That solution isn t very elegant. Also, it might not actually work! If original variable is declared as const, casting away const is not guaranteed to work on all implementations. For example, system might apply access constraints to the memory used by the variable Example: Date d1; const Date d2; string s1 = d1.stringrep(); string s2 = d2.stringrep(); //??? s2 is not guaranteed to have a valid result across all implementations
9 Mutable Data-Members Better solution is to use the mutable keyword class Date {... mutable string cache; mutable bool cachevalid; void updatecachevals() const; public:... string stringrep() const; }; Compiler will ensure that cache can be changed, even on variables declared const mutable means can never be const
10 Mutable Data-Members (2) Implementation of stringrep() gets simpler: string Date::stringRep() const { if (!cachevalid) { // Only mutable data-members are changed. updatecachevals(); cachevalid = true; } return cache; } And this also works now: Date d1; const Date d2; string s1 = d1.stringrep(); string s2 = d2.stringrep(); // OK!
11 Proper Uses of const_cast const_cast is best for situations when a function doesn t use const, but it ought to! The function doesn t change the argument, but argument wasn t declared const (usually by mistake) Example: dealing with bad standard libraries size_t strlen(char *s); // should be const char * const char *prompt = "Shall we play a game?"; size_t length = strlen(const_cast<char*>(prompt)); Very uncommon situation! You shouldn t need const_cast very often
12 Static Casts static_cast converts between related types static_cast<t>(value) Converts value to type T Only uses static type information (compile-time check) Example use-cases: Convert from an integral type to an enumeration Convert from a floating-point type to an integral type Convert from one pointer-type to another Typically, within the same class hierarchy Example: int *p = static_cast<int*>(malloc(100 * sizeof(int))); malloc() returns a void* which needs to be casted
13 Dynamic Casts dynamic_cast converts between types in a class hierarchy, using run-time type information dynamic_cast<t>(value) T must be a pointer or reference to a polymorphic type (a class with virtual member-functions) Performs a run-time type-check to see if value can be cast to T If so, conversion takes place and result has type T If not, dynamic_cast evaluates to 0! Mainly used to cast a base-class pointer/reference to a derived class. Has very complex behavior with multiple inheritance!
14 Static and Dynamic Casts Static casts are faster than dynamic casts Compile-time check vs. a runtime check Static casts can t move down a class hierarchy Requires run-time information about objects Example: class Widget { }; class SpecialWidget : public Widget { }; Widget *pw = new SpecialWidget(); // COMPILE ERROR: static type of pw is Widget* SpecialWidget *spw = static_cast<specialwidget*>(pw); // OK: pw points to a SpecialWidget SpecialWidget *spw = dynamic_cast<specialwidget*>(pw);
15 Static and Dynamic Cast Examples Dialog *d = new Dialog(); Window *w = static_cast<window *>(d); // OK, compile-time check (fast) Button *b = new Button(); Component *c = dynamic_cast<component *>(b); // OK, runtime check (slower) Component Window Button Dialog Button *b2; b2 = static_cast<button *>(c); b2 = dynamic_cast<button *>(c); // COMPILE ERROR // OK, b2 == b Dialog *d2; d2 = static_cast<dialog *>(b); d2 = dynamic_cast<dialog *>(b); // COMPILE ERROR // OK, d2 == 0
16 Reinterpreting Values reinterpret_cast<t>(value) Converts between unrelated types Again, converts value to type T Example use-cases: Convert an integer to a pointer, or vice versa Convert a pointer to a completely unrelated pointer type If destination type is same bit-width, the result s bit-pattern is same as the source s bit-pattern Should need reinterpret_cast very rarely If you do need it, encapsulate this functionality inside a class, and don t expose it to others! (Make sure you really do need it!)
17 Reinterpreting Values (2) Example: An API that represents windows and other GUI components with handles /** Clears the specified window. **/ void clearwindow(int handle) { Window *pwnd = reinterpret_cast<window*>(handle);... } API users aren t exposed to implementation details A safer solution? The API could use an STL map (or hash_map) to associate integer handles with GUI components Slower, but less likely to fail spectacularly!
18 The Point Class-Template (a review) template<class T> class Point { T x_coord, y_coord; public: Point() : x_coord(0), y_coord(0) {} Point(T x, T y) : x_coord(x), y_coord(y) {} T getx() { return x_coord; } void setx(t x) { x_coord = x; }... }; Parameterized on coordinate-type, named T class T means any type, not just classes Can use typename instead of class means same thing
19 Other Template Paramters Can parameterize templates on constants template<class T, int dim> class SquareMatrix { protected: T values[dim * dim]; public: }; SquareMatrix() { setidentity(); } ~SquareMatrix() { }... Type and dimension are template-parameters Allocation is static, so no delete in destructor
20 A Vector Template Write a generic vector-template: template <class T> class Vector { T *vals; int size; public: Vector(); explicit Vector(int size); T& elem(int i) { return vals[i]; }... // etc. }; Can instantiate template for various types: Vector<int> vints; Vector<string> vstrs; Vector<Shape*> vshapeptrs; Vector<Node*> vnodeptrs;
21 Specialized Vectors! Could specialize Vector<bool> s storage Instead of one byte/word per bool, store each bool value in a bit (a bit-packed representation) Provide a specialization of Vector template template <> class Vector<bool> { int *packedvals; int size; public:... bool& elem(int i) {... } }; All Vector<bool> variables use this specialization Specialized version is a separate class-template Must implement all the members, etc.
22 More Vector Specialization Vector<T> typically used to store pointers When T is a class, avoids slicing and polymorphism issues Can lead to code-bloat too! C++ compilers typically replicate template-code for each instantiation Lots of different Vector<T> instantiations will mean larger binary-file size Solution: specialize Vector for pointer-types
23 Specializing Vector for Pointers (1) Implement a special version of Vector<T> template <> class Vector<void*> { // Array of void* values void **vals; int size; public:... void* & elem(int i) {... } }; Provides base implementation for all Vectors of pointers but is only used for Vector<void*> variables!
24 Specializing Vector for Pointers (2) Next, provide a partial specialization of Vector template <class T> class Vector<T*> : private Vector<void*> { // Vector<void*> provides data-members, etc. public: typedef Vector<void*> Base; Vector() { } explicit Vector(int size) : Base(size) { }... T* & elem(int i) { return reinterpret_cast<t* &>(Base::elem(i)); } }; User specifies T* (e.g. Vector<Shape*>) Compiler uses Vector<T*> with Shape for T
25 Specializing Vector for Pointers (3) Why subclass with private modifier? template <class T> class Vector<T*> : private Vector<void*> { Use Vector<void*> implementation in Vector<T*> Don t want to expose Vector<void*> interface! private allows a class to use parent-class functionality, without affecting its own interface Why reinterpret_cast? T* & elem(int i) { } return reinterpret_cast<t* &>(Base::elem(i)); The void* is reinterpreted as a completely different type
26 Analysis of Vector-Approach Vector<void*>, etc. is some nasty code void* is rarely a good idea: untyped pointers Same with reinterpret_cast ignoring types! There are definite, measurable benfits: Far less template code generated by this method Compiled programs are smaller, faster Compile times can also be dramatically reduced Needed infrequently, but a very effective technique!
27 Subclassing Templates You write a template for a base-class: template<typename T> class Base { public: void f() { } }; Then you write a template for a derived class: template<typename T> class Derived : public Base<T> { public: void g() { f(); } }; This code won t compile!
28 Subclassing Templates (2) Inside Derived<T>::g(), the name f doesn t depend on the template-parameter T template<typename T> class Derived : public Base<T> { public: void g() { f(); } }; Known as a nondependent name Compiler doesn t look in dependent base-classes when looking up nondependent names i.e. compiler doesn t check Base<T> when looking for f
29 Subclassing Templates (3) Use this->f() instead of just f() this is always implicitly dependent in a template e.g. this has a type of Derived<T>* in this example Use Base<T>::f() instead of just f() Don t do this if f is virtual! You might not get the right results.
30 More Template Subclassing Fun You write this: void f() { } // A global function f template<typename T> class Base { public: void f() { } }; template<typename T> class Derived : public Base<T> { public: void g() { f(); } }; This code does compile!
31 More Template Subclassing Fun (2) When compiler tries to resolve f, it searches enclosing scope of Derived<T> That scope contains the global function f Qualified name of f is ::f() The code compiles, and ::f() is called instead of Base<T>::f() Moral: Be very careful when subclassing templates! Often need this-> or Base<T>:: for base-class member access, when deriving from a template
32 This Week s Assignment Small project (emphasis on small ) Experiment with something interesting to you The Standard Template Library C++ multiple-inheritance Create some templates Write some interesting program or utility Progress check-up in a week
CS11 Introduction to C++ Fall Lecture 6
CS11 Introduction to C++ Fall 2006-2007 Lecture 6 Today s Topics C++ exceptions Introduction to templates How To Report Errors? C style of error reporting: return values For C Standard Library/UNIX functions,
More informationOBJECT 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 informationECE 3574: Dynamic Polymorphism using Inheritance
1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:
More informationW3101: 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 informationCS11 Advanced C++ Fall Lecture 3
CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors
More informationWhere do we stand on inheritance?
In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public
More informationC++ 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 informationThese new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.
asting in C++: Bringing Safety and Smartness to Your Programs of 10 10/5/2009 1:20 PM By G. Bowden Wise The new C++ standard is full of powerful additions to the language: templates, run-time type identification
More informationTokens, 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 informationLaboratorio di Tecnologie dell'informazione. Ing. Marco Bertini
Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced
More informationPOLYMORPHISM 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 informationPOLYMORPHISM 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 informationLaboratorio di Tecnologie dell'informazione
Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced
More informationAppendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.
A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators
More informationG52CPP C++ Programming Lecture 15
G52CPP C++ Programming Lecture 15 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 IMPORTANT No optional demo lecture at 2pm this week Please instead use the time to do your coursework I
More information1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)
Answers to 2008/2009 G52CFJ exam Below are the answers to last year s exam, so that you can check how you did. In many cases I have given an example answer and an idea of what elements we would look for.
More informationCOMP322 - Introduction to C++ Lecture 09 - Inheritance continued
COMP322 - Introduction to C++ Lecture 09 - Inheritance continued Dan Pomerantz School of Computer Science 11 March 2012 Recall from last time Inheritance describes the creation of derived classes from
More informationcs3157: 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 informationC++ Coding Standards and Practices. Tim Beaudet March 23rd 2015
C++ Coding Standards and Practices Tim Beaudet (timbeaudet@yahoo.com) March 23rd 2015 Table of Contents Table of contents About these standards Project Source Control Build Automation Const Correctness
More informationLecture 20: templates
CIS 330:! / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 20:
More informationCh. 3: The C in C++ - Continued -
Ch. 3: The C in C++ - Continued - QUIZ What are the 3 ways a reference can be passed to a C++ function? QUIZ True or false: References behave like constant pointers with automatic dereferencing. QUIZ What
More informationShort 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 informationCS11 Introduction to C++ Fall Lecture 7
CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,
More informationCS201 - 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 informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationPolymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University
Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p
More informationFast 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 informationWelcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.
Welcome to Teach Yourself p. viii Acknowledgments p. xv Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. 6 Standard C++: A Programming Language and a Library p. 8
More informationQUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:
QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the
More informationCS11 Advanced C++ Spring 2018 Lecture 2
CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationCS3157: 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 informationChapter 17 vector and Free Store. Bjarne Stroustrup
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationCSE 333 Lecture C++ final details, networks
CSE 333 Lecture 19 -- C++ final details, s Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW3 is due in 5 days! - we re up to 6 bugs for you to patch
More informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428
More informationC++ Inheritance II, Casting
C++ Inheritance II, Casting CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationCS105 C++ Lecture 7. More on Classes, Inheritance
CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.
More informationIntroduction to C++ with content from
Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup
More informationSixth lecture; classes, objects, reference operator.
Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours
More informationDr. Md. Humayun Kabir CSE Department, BUET
C++ Type Casting Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Converting a value of a given type into another type is known as type-casting. ti Conversion can be implicit or explicit 2 C++
More informationAdvanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns
Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns This Advanced C++ Programming training course is a comprehensive course consists of three modules. A preliminary module reviews
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationOverview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading
HOW C++ WORKS Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++
More informationExercise 6.2 A generic container class
Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input
More informationBasic Types, Variables, Literals, Constants
Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic
More informationC++ Alexander Baltatzis
C++ Alexander Baltatzis Recap Undefined behaviour int * q1 = new int[2]; delete q1; int * q2 = new int; delete [] q2; Contract with the compiler constructor How would you implement delete [] Classes with
More informationOperators. The Arrow Operator. The sizeof Operator
Operators The Arrow Operator Most C++ operators are identical to the corresponding Java operators: Arithmetic: * / % + - Relational: < = >!= Logical:! && Bitwise: & bitwise and; ^ bitwise exclusive
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationPreface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.
Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using
More informationAnnouncements. Working on requirements this week Work on design, implementation. Types. Lecture 17 CS 169. Outline. Java Types
Announcements Types Working on requirements this week Work on design, implementation Lecture 17 CS 169 Prof. Brewer CS 169 Lecture 16 1 Prof. Brewer CS 169 Lecture 16 2 Outline Type concepts Where do types
More informationIntroduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1
Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:
More informationOverload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018
Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1 Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences
More informationME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types
ME240 Computation for Mechanical Engineering Lecture 4 C++ Data Types Introduction In this lecture we will learn some fundamental elements of C++: Introduction Data Types Identifiers Variables Constants
More informationModernizing legacy C++ code
Modernizing legacy C++ code Marius Bancila mariusbancila marius.bancila Agenda Short intro Legacy and modernization Good practices Q&A Containers Resource management correctness Const correctness Type
More informationOBJECT 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 informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 08 - Inheritance continued School of Computer Science McGill University March 8, 2011 Last Time Single Inheritance Polymorphism: Static Binding vs Dynamic
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationCpt 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 informationImportant From Last Time
Important From Last Time Volatile is tricky To write correct embedded C and C++, you have to understand what volatile does and does not do Ø What is the guarantee that it provides? Don t make the 8 mistakes
More informationIntroduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language
Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also
More informationProgramming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire
More informationJAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)
Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202
More informationIncreases Program Structure which results in greater reliability. Polymorphism
UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 20 November 14, 2016 CPSC 427, Lecture 20 1/19 Templates Casts and Conversions CPSC 427, Lecture 20 2/19 Templates CPSC 427, Lecture 20
More informationOverview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading
How C++ Works 1 Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++
More informationPage 1. Stuff. Last Time. Today. Safety-Critical Systems MISRA-C. Terminology. Interrupts Inline assembly Intrinsics
Stuff Last Time Homework due next week Lab due two weeks from today Questions? Interrupts Inline assembly Intrinsics Today Safety-Critical Systems MISRA-C Subset of C language for critical systems System
More informationPIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics
PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.
More informationFibonacci in Lisp. Computer Programming: Skills & Concepts (CP1) Programming Languages. Varieties of Programing Language
Fibonacci in Lisp Computer Programming: Skills & Concepts (CP1) Programming Languages (defun fibonacci (n) (if (or (= n 0) (= n 1)) 1 (+ (fibonacci (- n 1)) (fibonacci (- n 2))))) 22nd November 2010 defun-
More informationC++ Inheritance II, Casting
C++ Inheritance II, Casting CSE 333 Summer 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu Administriia
More informationCS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II
CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II Example: Simple variables Handout written by Julie Zelenski and Nick Parlante A variable is a location in memory. When a variable
More informationCSE 12 Week Eight, Lecture One
CSE 12 Week Eight, Lecture One Heap: (The data structure, not the memory area) - A binary tree with properties: - 1. Parent s are greater than s. o the heap order - 2. Nodes are inserted so that tree is
More informationC++ Inheritance and Encapsulation
C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members
More informationLecture 10: building large projects, beginning C++, C++ and structs
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 10:
More informationCourse Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++
Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationVector and Free Store (Pointers and Memory Allocation)
DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides
More informationThe Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured
Introduction p. xxix The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Language p. 6 C Is a Programmer's Language
More informationPointer Basics. Lecture 13 COP 3014 Spring March 28, 2018
Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory
More informationCOMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli
COMS W3101 Programming Language: C++ (Fall 2015) ramana@cs.columbia.edu Lecture-2 Overview of C continued C character arrays Functions Structures Pointers C++ string class C++ Design, difference with C
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance
More informationWeek 7. Statically-typed OO languages: C++ Closer look at subtyping
C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula
More informationPolymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.
Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)
More informationFrom Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009
From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3 Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009 C++ Values, References, and Pointers 1 C++ Values, References, and Pointers 2
More informationAssignment 1: grid. Due November 20, 11:59 PM Introduction
CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,
More informationCOMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli
COMS W3101 Programming Language: C++ (Fall 2015) ramana@cs.columbia.edu Lecture-2 Overview of C continued C character arrays Functions Structures Pointers C++ string class C++ Design, difference with C
More informationTopics. bool and string types input/output library functions comments memory allocation templates classes
C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers
More informationD Programming Language
Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take
More informationJayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT
CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions
More informationCOMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli
COMS W3101 Programming Language: C++ (Fall 2016) ramana@cs.columbia.edu Lecture-2 Overview of C C++ Functions Structures Pointers Design, difference with C Concepts of Object oriented Programming Concept
More information6.S096 Lecture 4 Style and Structure
6.S096 Lecture 4 Style and Structure Transition from C to C++ Andre Kessler Andre Kessler 6.S096 Lecture 4 Style and Structure 1 / 24 Outline 1 Assignment Recap 2 Headers and multiple files 3 Coding style
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using
More informationCS201 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 informationRecords. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05
Records CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 15: Objects 25 Feb 05 Objects combine features of records and abstract data types Records = aggregate data structures Combine several
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.
More informationOverload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019
Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 1 Introduction Prologue Definition of Function Overloading Determining which Overload to call How Works Standard Conversion Sequences Examples
More information