GEA 2017, Week 4. February 21, 2017
|
|
- Olivia Lewis
- 6 years ago
- Views:
Transcription
1 GEA 2017, Week 4 February 21, Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function, a temporary object is created which will be destroyed after foo(...) returns. In the body of foo(...), another local object x is created, whose copy assignment operator gets later called with par as an argument. Since, we have not overloaded the copy assignment operator ourselves, the compiler has generated the default one which just copies all of the members using their assignment operators. In this case, the x member in both objects points to the same memory location. Just before foo(...) returns, x will be destroyed essentially calling free from the standard library and freeing the memory pointed to by x. Afterwards, par will be destroyed. Since its member x also points to the same memory location, free gets called on an already freed memory buffer. If we had implemented a move assignment operator or move constructor, then the copy assignment operator would not have been automatically generated. Actually, it would have been declared, but deleted and thus its usage forbidden! In our case, there really isn t any reason we should not follow the rule of 5 and overload additionally the move assigment operator, move constructor, copy constructor and copy assigment operator. X e x p l i c i t X( int s z = 10) : s z ( s z ), x (new int [ s z ] ) f o r ( int i = 0 ; i < sz ; ++i ) x [ i ] = 0 ; X( ) delete [ ] x ; X( const X& r h t ) : s z ( r h t. s z ), x (new int [ r h t. s z ] ) // copy d a t a s t d : : copy ( r h t. x, r h t. x + r h t. s z, x ) ; X(X&& r h t ) noexcept : s z ( r h t. s z ), 1
2 x ( r h t. x ) r h t. s z = 0 ; r h t. x = n u l l p t r ; X& operator=(x&& r h t ) noexcept i f ( t h i s == &r h t ) // d e s t r o y o b j e c t s a l l o c a t e d d a t a delete [ ] x ; // s t e a l d a t a from r h t s z = r h t. s z ; r h t. s z = 0 ; x = r h t. x ; r h t. x = n u l l p t r ; X& operator=(const X& r h t ) i f ( t h i s == &r h t ) // A l l o c a t e new b u f f e r. We f i r s t a l l o c a t e t h e memory b e f o r e c h a n g i n g t h e s t a t e i n any way. // T h i s p r o v i d e s t h e s t r o n g e x c e p t i o n g u a r a n t e e. int tmp = new int [ r h t. s z ] ; s z = r h t. s z ; // D e s t r o y o b j e c t s a l l o c a t e d d a t a. delete [ ] x ; x = tmp ; // copy d a t a s t d : : copy ( r h t. x, r h t. x + r h t. s z, x ) ; private : int s z, x ; ; void foo ( const X& par ) X x ; x = par ; f o o (X( ) ) ; 2. Problem 2 (a) inline specifier The inline specifiers instruct the compiler that the prefered calling mechanism is to insert the body of the function instead of the default calling mechanism. Whether the compiler will comply is implementation dependent. Compilers usually have stronger specifiers like forceinline under MSVC. A function cannot always be inlined for various reasons: On some systems there can be a strict limit on the size of the executable program which renders inlining unfavourable. (b) include guards A way to prevent the same defition to be added multiple times in a translation unit. 2
3 Example: File Hello.hpp: #i f n d e f HELLO HPP #define HELLO HPP H e l l o ; #endif // HELLO HPP File Something.hpp #i f n d e f SOMETHING HPP #define SOMETHING HPP #include Hello. hpp void p r i n t S t u f f ( const H e l l o &smt ) ; #endif // SOMETHING HPP File main.cpp #include #include Hello. hpp Something. hpp p r i n t S t u f f ( H e l l o ( ) ) ; If there weren t include guards in Hello.hpp, then there would have been a compilation error as the class Hello would have been defined twice. Mistakes can happen whenever include guards are used. For example, one might check for one macro being defined, but define another after the check. One might also check/define the same macro in multiple headers. #pragma once is not part of the standard, but it is widely supported. (c) pure virtual function A virtual function with added a pure-specifier. If you check the C++11 grammar, you can see that the pure-specifier is just = 0. If a class has a pure virtual function, it cannot be instantiated and thus becomes an abstract class. The class can be only used as a base class. If the derived class does not declare all pure virtual functions without the pure-specifier, then it is also an abstract class. You can consult the C++11 standard, 10.4 Abstract classes for more cases. Also, an implementation can be provided to a pure virtual function. ; X v i r t u a l void print ( ) = 0 ; void X : : p r i n t ( ) cout << X p r i n t s << e n d l ; Y : public X 3
4 ; void p r i n t ( ) o v e r r i d e cout << Y p r i n t s << e n d l ; Z : public X void p r i n t ( ) o v e r r i d e X : : p r i n t ( ) ; ; X t1 = new Y( ) ; X t2 = new Z ( ) ; t1 >p r i n t ( ) ; // Y p r i n t s t2 >p r i n t ( ) ; // X p r i n t s (d) virtual destructor If a destructor is declared virtual in a base class, the derived class destructor will be implicitly declared virtual as well. This will guarantee that whenever delete gets called, the most-derived class destructor will be called all up to the base s class destructor (in reverse order of the constructors being called). ; X v i r t u a l X( ) cout << d e l X << endl ; Z : public X Z ( ) // i m p l i c i t l y v i r t u a l cout << d e l Z << endl ; ; D : public Z D( ) // i m p l i c i t l y v i r t u a l cout << d e l D << endl ; ; Z t = new D( ) ; delete t ; It prints: del D del Z del X (e) private inheritance A 4
5 .. a n y t h i n g e l s e needed.. ; int mpublicdata ; protected : int mprotecteddata ; private : int mprivatedata ; B : private A.. o t h e r s t u f f h e r e.. Because B inherits from A privately, any member method of B can access the public and protected fields of A. However, non of A s members can be accessed through an instance of B. For example: A a (new A( ) ) ; // j u s t f i n e b e c a u s e mpublicdata i s p u b l i c and can b e a c c e s s e d t h r o u g h an i n s t a n c e o f A. a >mpublicdata = 1 ; B b (new B ( ) ) ; // n o t f i n e, b e c a u s e a c c e s s i n g mpublicdata t h r o u g h // a B i n s t a n c e would b e t h e same a s i f we a r e a c c e s s i n g a p r i v a t e member. b >mpublicdata = 1 ; (f) scoped enumeration An alternative to plain enum in which the enumerators do not pollute the global scope. Example: enum ; Color red, black enum Animal : int dog, cat ; Color c1 = red ; // r e d i s a r e s e r v e d name int c2 = b l a c k ; // c a s t s t o i n t Animal a1 = Animal : : dog ; // h a s t o a c c e s s t h e c o r r e c t s c o p e f i r s t int a2 = s t a t i c c a s t <int >(Animal : : c a t ) ; // h a s t o b e e x p l i c i t l y c a s t e d t o i n t 3. Problem 3 There are many different situations in which one would rely on C pointers: (a) Libraries or the code base require it. (b) Complying with the coding standard. For example, check under Other C++ Features. (c) Whenever a reference cannot be initialized at the moment of declaration. 5
6 S l i d e r S l i d e r ( ) : mboundvalue ( n u l l p t r ) // e v e r y t h i n g e l s e r e q u i r e d void bindtoslider ( f l o a t var ) mboundvariable = var ; private : f l o a t mboundvariable ; The example above is a Slider which receives a slider by the user. Initially, there is no bound variable to the slider. Thus, we cannot have mboundvariable to be a reference. Very much similarly we cannot use reference types in containers which require copying. I.e. std :: vector < MyT ype& > will result in a compilation error. Note that one can use std :: reference wrapper < MyT ype >, but it really just wraps a MyType pointer. Smart pointers are a way of preventing memory leaks, but they are still not great. One still has to think of the ownership of resources. Possibly a rule of thumb is to initialize pointers immediately - either to nullptr or make them point to the appropriate place in memory. After freeing the memory they point to, one should set them to point to nullptr again. In this way, one can void double freeing the same buffer. How to use headers: Possibly put inline functions in files ending in.inl, the other declarations can go in the.h or.hpp files. Usually a problem in big projects is build time (try to compile Chromium from scratch). Possibly forward declare as often as possible. Always include the smallest amount of required headers. Precompile heavy headers. How to use namespaces: Possibly create namespaces for the different modules. I.e. namespace math, namespace graphics, etc. If you have something local to the translation unit, put it into an unnamed namespace. I.e. namespace GLuint GenerateBuffersAndFillRandomData ( int n ) GLuint b u f f e r ; // do a l l o f t h e i n i t i a l i z a t i o n and f i l l t h e random d a t a return b u f f e r ; // namespace namespace g r a p h i c s 6
7 // o t h e r s t u f f MyRandomEffect : : i n i t B u f f e r s ( ) mbuffer = GenerateBuffersAndFillRandomData ( m B u f f e r S i z e ) ; // namespace g r a p h i c s 4. Problem 4 One can use smart pointers so that some of the work around memory management is reduced. Still, there are many other issues to address regarding memory management. In some cases, a whole bunch of objects have the same life span. Consider a particle system: particles are alive for a given amount of time and afterwards their state gets restarted. There is often no need to create more particles. Once there is no longer need of the particle system, all of the particle objects have to be destroyed. Another example can be a parser in a compiler: it goes through all of the tokens generated by a lexer, it creates and updates new nodes and at the end we have an abstract syntax tree. All of the memory used by the nodes will have to be freed after compilation is done, but while the existence of the AST none of them have to be freed. The pattern which arises is that freeing of memory for all of the objects is done at once. Both examples would benefit from a pool allocator. This would require also overloading the new and delete operators in the corresponding classes. Some projects add their own macro for that and put it into class declaration. You can check here for a reference: On the other hand, in a particle system simulator there is often data parallelism to be exploited which calls for the use of some wide-type instruction sets like the AVX instruction set. Loading data into registers requires the data to be 32-byte alligned for AVX (unless you are using the instrinsics for unanligned data). Unfortunately, the standard allocator does not allow us to do that. So, if one wants to put all of the data into an std::vector, it would not be possible without passing our own aligned allocator. An example: 7
Midterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More informationA brief introduction to C++
A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
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 informationObject Oriented Design
Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following
More informationRecharge (int, int, int); //constructor declared void disply();
Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize
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 informationWentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.
Lecture 14 1 Exceptions Iterators Random numbers Casting Enumerations Pairs The Big Three Outline 2 Error Handling It is often easier to write a program by first assuming that nothing incorrect will happen
More informationModern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi
Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance
More informationOutline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O
Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references
More information04-19 Discussion Notes
04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object
More informationObject Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:
Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Section 1 Multiple Choice Questions (40 pts total, 2 pts each): Q1: Employee is a base class and HourlyWorker is a derived class, with
More informationA class is a user-defined type. It is composed of built-in types, other user-defined types and
Chapter 3 User-defined types 3.1 Classes A class is a user-defined type. It is composed of built-in types, other user-defined types and functions. The parts used to define the class are called members.
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationCS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()
More information04-17 Discussion Notes
04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should
More information1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!
//Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new
More informationCMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am
CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103
More informationIntroduction Of Classes ( OOPS )
Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationIntroducing C++ to Java Programmers
Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:
More informationOperating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst
Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively
More informationAdvanced Systems Programming
Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short
More informationException Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011
More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors
More informationCOMP6771 Advanced C++ Programming
1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout
More informationC++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis
C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related
More informationCS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4
CS32 - Week 4 Umut Oztok Jul 15, 2016 Inheritance Process of deriving a new class using another class as a base. Base/Parent/Super Class Derived/Child/Sub Class Inheritance class Animal{ Animal(); ~Animal();
More informationG52CPP C++ Programming Lecture 20
G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not
More informationCOMP6771 Advanced C++ Programming
1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors
More informationthe gamedesigninitiative at cornell university Lecture 7 C++ Overview
Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example
More informationCOMP 2355 Introduction to Systems Programming
COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract
More informationC++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13
C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 This chapter focuses on introducing the notion of classes in the C++ programming language. We describe how to create class and use an object of a
More information377 Student Guide to C++
377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided
More information3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.
3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.
More informationImplementing an ADT with a Class
Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the
More informationPIC 10A Objects/Classes
PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous
More informationexplicit class and default definitions revision of SC22/WG21/N1582 =
Doc No: SC22/WG21/ N1702 04-0142 Project: JTC1.22.32 Date: Wednesday, September 08, 2004 Author: Francis Glassborow & Lois Goldthwaite email: francis@robinton.demon.co.uk explicit class and default definitions
More informationConsider the program...
Smart Pointers Consider the program... When the scope of foo is entered storage for pointer x is created The new allocates storage on the heap class X {... When the scope foo is left, the storage for x
More information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
More informationClass Destructors constant member functions
Dynamic Memory Management Class Destructors constant member functions Shahram Rahatlou Corso di Programmazione++ Roma, 6 April 2009 Using Class Constructors #include Using std::vector; Datum average(vector&
More informationProgramming in C++: Assignment Week 8
Programming in C++: Assignment Week 8 Total Marks : 20 September 9, 2017 Question 1 Consider the following code segment. Mark 2 void myfunction(int test) { try { if (test) throw test; else throw "Value
More informationy
The Unfit tutorial By Dr Martin Buist Initial version: November 2013 Unfit version: 2 or later This tutorial will show you how to write your own cost function for Unfit using your own model and data. Here
More information1 Short Answer (5 Points Each)
1 Short Answer ( Points Each) 1. Find and correct the errors in the following segment of code. int x, *ptr = nullptr; *ptr = &x; int x, *ptr = nullptr; ptr = &x; 2. Find and correct the errors in the following
More informationADTs in C++ In C++, member functions can be defined as part of a struct
In C++, member functions can be defined as part of a struct ADTs in C++ struct Complex { ; void Complex::init(double r, double i) { im = i; int main () { Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0,
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 informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
More informationClass and Function Templates
Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing
More informationReliable C++ development - session 1: From C to C++ (and some C++ features)
Reliable C++ development - session 1: From C to C++ (and some C++ features) Thibault CHOLEZ - thibault.cholez@loria.fr TELECOM Nancy - Université de Lorraine LORIA - INRIA Nancy Grand-Est From Nicolas
More informationMotivation for Templates. Class and Function Templates. One Way to Look at Templates...
Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates...
More informationG52CPP C++ Programming Lecture 13
G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 X Cynthia Lee Topics: Last week, with Marty Stepp: Making your own class Arrays in C++ This week: Memory and Pointers Revisit some topics from last week Deeper look at
More informationCh. 12: Operator Overloading
Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42
More informationObject-Oriented Programming, Iouliia Skliarova
Object-Oriented Programming, Iouliia Skliarova CBook a = CBook("C++", 2014); CBook b = CBook("Physics", 1960); a.display(); b.display(); void CBook::Display() cout
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 informationPointers. Developed By Ms. K.M.Sanghavi
Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create
More informationIntroduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005
Introduction to C++ Part II Søren Debois Department of Theoretical Computer Science IT University of Copenhagen September 12th, 2005 Søren Debois (Theory, ITU) Introduction to C++ September 12th, 2005
More informationSuppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }
Multiple choice questions, 2 point each: 1. What output is produced by the following program? #include int f (int a, int &b) a = b + 1; b = 2 * b; return a + b; int main( ) int x=1, y=2, z=3;
More informationCopy Control 2008/04/08. Programming Research Laboratory Seoul National University
Copy Control 2008/04/08 Soonho Kong soon@ropas.snu.ac.kr Programming Research Laboratory Seoul National University 1 Most of text and examples are excerpted from C++ Primer 4 th e/d. 2 Types control what
More informationC++_ MARKS 40 MIN
C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float
More informationRvalue References, Move Semantics, Universal References
Rvalue References, Move Semantics, Universal References PV264 Advanced Programming in C++ Nikola Beneš Jan Mrázek Vladimír Štill Faculty of Informatics, Masaryk University Spring 2018 PV264: Rvalue References,
More informationScope. Scope is such an important thing that we ll review what we know about scope now:
Scope Scope is such an important thing that we ll review what we know about scope now: Local (block) scope: A name declared within a block is accessible only within that block and blocks enclosed by it,
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main
More informationSmart Pointers. Some slides from Internet
Smart Pointers Some slides from Internet 1 Part I: Concept Reference: Using C++11 s Smart Pointers, David Kieras, EECS Department, University of Michigan C++ Primer, Stanley B. Lippman, Jesee Lajoie, Barbara
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 information05-01 Discussion Notes
05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer
More informationVector and Free Store (Vectors and Arrays)
DM560 Introduction to Programming in C++ Vector and Free Store (Vectors and Arrays) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides by Bjarne
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More informationPaytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value
Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object
More informationDiscussion 1E. Jie(Jay) Wang Week 10 Dec.2
Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the
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 informationCSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC
CSCI 262 Data Structures 9 Dynamically Allocated Memory POINTERS AND ARRAYS 2 Arrays Arrays are just sequential chunks of memory: Arrays and Pointers Array variables are secretly pointers: x19 x18 x17
More informationC++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.
C++11: 10 Features You Should be Using Gordon Brown @AerialMantis R&D Runtime Engineer Codeplay Software Ltd. Agenda Default and Deleted Methods Static Assertions Delegated and Inherited Constructors Null
More informationKOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationCSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation
CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation Review from Lectures 7 Algorithm Analysis, Formal Definition of Order Notation Simple recursion, Visualization
More information15: Polymorphism & Virtual Functions
15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer
More informationPolymorphism Part 1 1
Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid
More information04-24/26 Discussion Notes
04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x
More informationCS 11 C++ track: lecture 1
CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/
More informationCS93SI Handout 04 Spring 2006 Apr Review Answers
CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly
More informationPointers II. Class 31
Pointers II Class 31 Compile Time all of the variables we have seen so far have been declared at compile time they are written into the program code you can see by looking at the program how many variables
More informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
More informationChapter 13: Copy Control. Overview. Overview. Overview
Chapter 13: Copy Control Overview The Copy Constructor The Assignment Operator The Destructor A Message-Handling Example Managing Pointer Members Each type, whether a built-in or class type, defines the
More informationC++ 8. Constructors and Destructors
8. Constructors and Destructors C++ 1. When an instance of a class comes into scope, the function that executed is. a) Destructors b) Constructors c) Inline d) Friend 2. When a class object goes out of
More informationObject Oriented Software Design II
Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February
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 informationRecap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff
Recap: Pointers IFMP 18, M. Schwerhoff int* int& *p &i &*&* ** * * * * A 0 A 1 A 2 A 3 A 4 A 5 A 0 A 1 A 2 A 3 A 4 A 5 5 i int* p; A 0 A 1 A 2 A 3 A 4 A 5 5 i p int* p; p = &i; A 0 A 1 A 2 A 3 A 4 A 5
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 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 informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationObject Oriented Software Design II
Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February
More informationChapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016
Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use
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 informationKLiC C++ Programming. (KLiC Certificate in C++ Programming)
KLiC C++ Programming (KLiC Certificate in C++ Programming) Turbo C Skills: Pre-requisite Knowledge and Skills, Inspire with C Programming, Checklist for Installation, The Programming Languages, The main
More informationCSC1322 Object-Oriented Programming Concepts
CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.
More information