Constructors and Assignment. Mike Precup

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "Constructors and Assignment. Mike Precup"

Transcription

1 Constructors and Assignment Mike Precup

2 Administrivia Actually important this time! Assignment 2 is due on Tuesday at midnight. I ll be holding LaiR hours from 8 PM - 10 PM on Sunday again.

3 Why Constructors? A constructor is a function which is called when an object is first created Objects are created on the stack by a variable declaration Objects on the heap are created with new The constructor sets up the initial state of the object for later functions This should be familiar, but let s go a bit more in depth...

4 Why Constructors? class Vector { Vector() { logicalsize = 0; allocatedsize = 8; elems = new int[allocatedsize]; } }; // Both of these lines call the constructor Vector x; Vector *y = new Vector();

5 Why Constructors? Why do objects have constructors? Can't we just use an init function which does the same thing the constructor does?

6 Why Constructors? struct foo { int value; void init(int v) {value = v;} }; foo x; x.init(42); cout << x.value << endl;

7 Why Constructors? Issue #1: What if we forgot x.init()? struct foo { int value; void init(int v) {value = v;} }; foo x; // x.init(42); cout << x.value << endl; // What s printed?

8 Why Constructors? Issue #2: I'm incredibly lazy. int main() { // Construct *and* initialize in one line HasAConstructor x(42); //.init() requires two lines! HasInitFunction y; y.init(42); }

9 Why Constructors? Issue #3: Const data members struct ConstMember { const int value; void init(int v) {value = v;} }; ConstMember x; x.init(42); // Error: assignment to const!

10 Why Constructors? The notion of initialization is fundamental to the C++ language and distinct from the notion of assignment.

11 Why Constructors? Initialization transforms an object s initial junk data into valid data. Assignment replaces existing valid data with other valid data.

12 Why Constructors? Initialization is defined by the constructor for a type. Assignment is defined by the assignment operator for a type.

13 Constructors We will be looking at three kinds of Constructors today Default Constructors What you are used to but with some new tricks Copy Constructors Construct an instance of a type to be a copy of another instance Copy Assignment Not really a constructor Assign an instance of a type to be a copy of another instance

14 Why Constructors? // Initialization: Default Constructor Widget x; // Initialization: Copy Constructor Widget y(x); // Initialization: Copy Constructor (form 2) Widget z = x; // Assignment: Copy assignment z = x;

15 Quick Note It is not always necessary to define all types of constructors and assignment. If you don t the compiler will create a default version for you

16 Constructors We will be looking at three kinds of Constructors today Default Constructors What you are used to but with some new tricks Copy Constructors Construct an instance of a type to be a copy of another instance Copy Assignment Not really a constructor Assign an instance of a type to be a copy of another instance

17 Default Constructors A constructor looks just like any other member function for a type, with 3 distinctions Constructors have no return value listed (not even void) Constructors have the same name as the type in question Constructors can have an initialization list

18 Default Constructors Initialization lists allow us to initialize (not assign) data members when we initialize our type. // Assignment struct Widget { const int value; Widget(); }; Widget::Widget() { value = 42; //ERROR } // Initialization struct Widget { }; const int value; Widget(); Widget::Widget() : value(42) {}

19 Default Constructors Initialization lists can have multiple parts struct Person { int age; string name; Person(); }; Person::Person() : age(36), name( Kanye ) { //Empty constructor since nothing to assign }

20 Default Constructors Constructors solve all 3 of the problems with the init function. Value is initialized to v, not assigned struct ConstMember { const int value; ConstMember(int v) : value(v) {} }; int main() { ConstMember b(42); // value is 42 }

21 Vector Constructors Let's now take a look at a more complex constructor -- our old friend Vector<T>.

22 Vector Constructors // Initialize an empty vector: vector<int> a; // 42 elements: all zero vector<int> b(42); // 42 elements: all set to 11 vector<int> c(42, 11);

23 Interlude: Default Parameters We re about to do something cool, but we need to review default parameters first.

24 Interlude: Default Parameters In C++, we can list default parameters for functions which take arguments Functions without default parameters can have their rightmost parameters omitted and the default values will be used The syntax is simple, but default parameters should only be listed in the declaration of a function, not the definition

25 Interlude: Default Parameters // Declare our default arguments void f(int a, int b = 5, int c = 42); // Define our function void f(int a, int b, int c) { cout << a << ; cout << b << ; cout << c << endl; }

26 Interlude: Default Parameters // Declare our default arguments void f(int a, int b = 5, int c = 42); // Define our function void f(int a, int b, int c) { cout << a << ; cout << b << ; cout << c << endl; } f(1); // f(1, 2); // f(1, 2, 3); // 1 2 3

27 Vector Constructors Let's try implementing the default and fill constructors in one step using default parameters.

28 Constructors We will be looking at three kinds of Constructors today Default Constructors What you are used to but with some new tricks Copy Constructors Construct an instance of a type to be a copy of another instance Copy Assignment Not really a constructor Assign an instance of a type to be a copy of another instance

29 Copy Constructors A copy constructor is called when an instance of a type is constructed from another instance Two ways it can be called //directly call the copy constructor int x(4); //implicitly call the copy constructor int y = 2;

30 Copy Constructors A copy constructor is called when an instance of a type is constructed from another instance Vector<string> a(10, hi ); //directly call the copy constructor Vector<string> b(a); //implicitly call the copy constructor Vector<string> c = a;

31 Copy Constructors Before writing the copy constructor, let's think about how we're going to write it. First idea: just copy all of their member variables We'll have the correct size and element pointer, so this works right? This is what the default copy constructor does

32 Copy Constructors ElemType* elems; vector<int> a: int logicalsize; int allocatedsize; 0 8 Vector<int> a;

33 Copy Constructors vector<int> a: ElemType* elems; 8 int logicalsize; int allocatedsize; 1 8 Vector<int> a; a.push_back(8);

34 Copy Constructors vector<int> a: ElemType* elems; 8 6 int logicalsize; int allocatedsize; 2 8 Vector<int> a; a.push_back(8); a.push_back(6);

35 Copy Constructors vector<int> a: ElemType* elems; int logicalsize; int allocatedsize; 3 8 Vector<int> a; a.push_back(8); a.push_back(6); a.push_back(7);

36 Copy Constructors vector<int> a: ElemType* elems; int logicalsize; int allocatedsize; 3 8 ElemType* elems; vector<int> b: int logicalsize; int allocatedsize; 3 8 Vector<int> a; a.push_back(8); a.push_back(6); a.push_back(7); Vector<int> b = a;

37 Copy Constructors vector<int> a: ElemType* elems; int logicalsize; int allocatedsize; 3 8 Changing the value of b also changed the value of a! ElemType* elems; vector<int> b: int logicalsize; int allocatedsize; 3 8 Vector<int> a; a.push_back(8); a.push_back(6); a.push_back(7); Vector<int> b = a; b[0] = 9;

38 Copy Constructors vector<int> a: ElemType* elems; int logicalsize; int allocatedsize; ElemType* elems; vector<int> b: int logicalsize; int allocatedsize; 3 8 Vector<int> a; a.push_back(8); a.push_back(6); a.push_back(7); Vector<int> b = a; b[0] = 9;

39 Copy Constructors If you have pointer member variables, you should always define a copy constructor

40 Copy Constructors Let's try implementing a proper copy constructor for vector in which we copy over the elements

41 Constructors We will be looking at three kinds of Constructors today Default Constructors What you are used to but with some new tricks Copy Constructors Construct an instance of a type to be a copy of another instance Copy Assignment Not really a constructor Assign an instance of a type to be a copy of another instance

42 Copy Assignment Now that we know how to write constructors, include the copy constructor, we're ready to move on to the copy assignment operator Remember, assignment takes an already initialized object and gives it new values int x = 4; //Copy Constructor x = 2; //Copy Assignment

43 Copy Assignment The syntax for copy assignment is as follows. Note that this is the same syntax as any other operator overload. class Widget { public: Widget& operator=(const Widget& other); //Other member vars and functions }; Widget& Widget::operator=(const Widget& other) { // Code to copy data from other }

44 Copy Assignment Implementing the copy assignment operator is tricky for a couple of reasons: Catching memory leaks Handling self assignment Understanding the return value

45 Copy Assignment I don't want to go through the gory details of how hard it is to write the truly optimal copy assignment operator. Instead, let's use the "copy and swap" idiom to do save ourselves the trouble! Not quite as efficient, but much, much cleaner

46 Copy Assignment The copy and swap idiom works as follows: We have an existing value we want to modify, and an existing value to read data from Use the copy constructor to create a temporary value from the value we're reading data from Swap the contents of the value to modify and the temporary

47 Copy Assignment class Widget { int value; public: void swap(widget& other); Widget& operator=(const Widget& other); }; void Widget::swap(Widget& other) { std::swap(value, other.value); } Widget& Widget::operator=(const Widget& other) { Widget temp(other); swap(temp); return *this; }

48 Copy Assignment We can improve this function a bit by handling the copying into a temporary by using pass by value

49 Copy Assignment class Widget { int value; public: void swap(widget& other); Widget& operator=(const Widget& other); }; void Widget::swap(Widget& other) { std::swap(value, other.value); } Widget& Widget::operator=(const Widget& other) { Widget temp(other); swap(temp); return *this; }

50 Copy Assignment class Widget { int value; public: void swap(widget& other); Widget& operator=(const Widget& other); }; void Widget::swap(Widget& other) { std::swap(value, other.value); } Widget& Widget::operator=(Widget other) { swap(other); return *this; }

51 Vector Assignment Let's take a look at how to do this in vector.

52 Some C++ Quirks While we are on the topic of constructors, what does this line of code do? Vector<int> v();

53 Some C++ Quirks While we are on the topic of constructors, what does this line of code do? int x(); //meant to do int x; or int x(2); This is called the most vexing parse and has plagued many a C++ programmer. By adding the parentheses, v is treated as a function declaration.

54 Some C++ Quirks In our copy constructor the following code will compile Vector<int> x = 15; To prevent accidental type conversions, use the explicit keyword before the declaration of your constructor

55 Some C++ Quirks A default constructor, copy constructor, and copy assignment operator will all be defined for you if you don t define them.

56 Some C++ Quirks The old way of removing them was to declare them as private, and never implement them. This would create a compiler error if anyone tried to use them. class Vector { private: }; Vector(const Vector& other); // No implementation

57 Some C++ Quirks The new way of removing them generates much nicer error messages, and works in all cases. Just set any you don t want equal to delete. class Vector { public: }; Vector(const Vector& other) = delete;

58 Rule of Three If you implement a copy constructor, assignment operator, or destructor, you should implement the others, as well

59 The Preprocessor It s time for a brief note about the preprocessor The preprocessor is the first stage of the compiler It does basic text manipulation Preprocessor directives are prefaced by #

60 #include The preprocessor isn t terribly intelligent. When you write #include, it s not doing anything fancy, it just copy pastes the file right in!

61 #include Say I have a header file that defines my Vector. If, in main.cpp, I write the following: #include vector.h #include vector.h It s going to define Vector twice!

62 #include Now, you might say, eh, I m smart enough not to write that twice. But sometimes, it s not so obvious: #include vector.h #include stack.h If stack uses vector, it s still going to be defined twice!

63 #ifndef The typical strategy for solving this problem is to use conditional inclusion of code These directives allow you to do that: #ifndef NAME Only include the following code is NAME is not defined (in the preprocessor!) #endif Close the conditional #define NAME Define NAME in the preprocessor

64 #ifndef The typical structure looks like this: #ifndef L_VECTOR_H_ #define L_VECTOR_H_ // header file code #endif Make sure you use a name that isn t taken anywhere else

65 #pragma once You ll sometimes see this in code, although it s not universally supported It basically just exactly what you just saw for the entire file If it s supported and you choose to use it, you can just add that one line to the top!

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova Data types define the way you use the storage (memory) in the programs. By specifying a data type, you tell the sompiler how to create a particular piece

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

Creating Functions in C/C++, Part 2

Creating Functions in C/C++, Part 2 Call-by-Reference Parameters What if we want to write a function that actually changes the value of its parameters? For example, suppose we want a function that can be called like this: swap(x,y) that

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 23, 2016 1 / 21 About this presentation 2 / 21 About this presentation This presentation is not about learning to program 2 / 21

More information

Advanced C++ Exception Handling Topic #5

Advanced C++ Exception Handling Topic #5 Advanced C++ Exception Handling Topic #5 CS202 5-1 CS202 5-2 Exception Handling Throwing an Exception Detecting an Exception Catching an Exception Examine an Example using Classes and Operator Overloading

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Operator Overloading; String and Array Objects

Operator Overloading; String and Array Objects 11 Operator Overloading; String and Array Objects The whole difference between construction and creation is exactly this: that a thing constructed can only be loved after it is constructed; but a thing

More information

A deeper look at Inline functions

A deeper look at Inline functions A deeper look at Inline functions I think it s safe to say that all Overload readers know what C++ inline functions are. When we declare a function or member function as inline we are trying to avoid the

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

Introduction to C++ Programming Vahid Kazemi

Introduction to C++ Programming Vahid Kazemi Introduction to C++ Programming Vahid Kazemi Overview An overview of C/C++ - Basic types, Pointers, Arrays, Program control, Functions, Arguments, Structures, Operator overloading, Namespaces, Classes,

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++

CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++ CS193D Handout 04 Winter 2005/2006 January 11, 2006 A Crash Course in C++ Most people taking CS193D will already have some experience with C++. This handout is a quick refresher in case it s been a while.

More information

Online C++ FAQ/Tutorial and Advanced Questions

Online C++ FAQ/Tutorial and Advanced Questions Online C++ FAQ/Tutorial and Advanced Questions Alexis Angelidis January 11, 2005 1 Quick notes to C programmers instead of macros use const or enum to define constants inline to prevent function call overload

More information

Introduction to C++ Data Abstraction w/ Classes Topic #2

Introduction to C++ Data Abstraction w/ Classes Topic #2 Introduction to C++ Data Abstraction w/ Classes Topic #2 CS202 2-1 Lecture #1 plus Review Abstract Data Types Introduction to...object Models Introduction to...data Abstraction Using Data Abstraction in

More information

STL Iterators, Part I

STL Iterators, Part I CS106L Winter 2007-2008 Handout #08 January 28, 2008 STL Iterators, Part I Introduction The STL comprises several different container types, from the linear vector to the associative map. To provide a

More information

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez! C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a

More information

Avancerad programmering i C++ 1

Avancerad programmering i C++ 1 Polymorphism Polymorphism and virtual Polymorphism - many forms In C++, polymorphism is implemented through virtual. Virtual (and so, of course, polymorphism) have a meaning only in the context of inheritance.

More information

Chapter Overview. Inheritance. Inheritance Basics. Inheritance. Parent and Child Classes. Inheritance Example Inheritance Basics

Chapter Overview. Inheritance. Inheritance Basics. Inheritance. Parent and Child Classes. Inheritance Example Inheritance Basics Chapter 15 Overview 15.1 Inheritance Basics Inheritance 15.2 Inheritance Details 15.3 Polymorphism Copyright 2008 Pearson Addison-Wesley. All rights reserved. Slide 15-2 15.1 Inheritance Inheritance Basics

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2016 Fall Exam 3 Friday, November 18, 2016 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2016 Fall Exam 3 Friday, November 18, 2016 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

C++ for Game Programmers

C++ for Game Programmers C++ for Game Programmers Course Description C++ has become one of the favourite programming language for game programmers. Reasons for wide spread acceptability of C++ are plenty, but primary reasons are,

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

More class design with C++ Member or non-member function? l Class operations are typically implemented as member functions Declared inside class

More class design with C++ Member or non-member function? l Class operations are typically implemented as member functions Declared inside class 1 2 3 4 More class design with C++ Member or non-member function? l Class operations are typically implemented as member functions Declared inside class definition Can directly access private members Usually

More information

CIS 190: C/C++ Programming. Lecture 13 Templates

CIS 190: C/C++ Programming. Lecture 13 Templates CIS 190: C/C++ Programming Lecture 13 Templates Overloading Functions Templates Outline Function Templates Compiler Handling & Separate Compilation Class Templates Declaring Constructors Defining Using

More information

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved. The Secret Partner Pattern Revision 3a by Bill Trudell, July 23, 2001 Submitted to the Pattern Languages of Programs Shepherd: Neil Harrison PC Member: Kyle Brown Thumbnail This paper describes the Secret

More information

Copy Constructors and Overloaded Assignment. CMSC 202, Version 3/02 1

Copy Constructors and Overloaded Assignment. CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment CMSC 202, Version 3/02 1 When do we make copies of an object? 1) When passing them to a function by value 2) When returning them from a function by value 3)

More information

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming OOP is a programming paradigm. It's key features are: Information hiding, Data abstraction, Encapsulation, Modularity, Polymorphism, and inheritance. Most programming languages

More information

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators This handout is designed to provide a better understanding of how one should write template code and architect iterators

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Missouri S&T Computer Science Department C++ Coding Standard

Missouri S&T Computer Science Department C++ Coding Standard Missouri S&T Computer Science Department C++ Coding Standard September 12, 2016 Contents 1 Introduction 2 1.1 Why do we need a coding standard?................ 2 1.2 Acknowledgements..........................

More information

CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011

CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011 CS201- Introduction to Programming Latest Solved Mcqs from Final term Papers July 11,2011 Mc100401285 moaaz.pk@gmail.com Moaaz Siddiq Bc100400662 bc100400662asad@gmail.com Asad Ali Latest Mcqs FINALTERM

More information

C++ CLASSES C/C++ ADVANCED PROGRAMMING

C++ CLASSES C/C++ ADVANCED PROGRAMMING C++ CLASSES C/C++ ADVANCED PROGRAMMING GOAL OF THIS LECTURE C++ classes Dr. Juan J. Durillo 2 (C++) CLASSES: BASIC CONCEPTS Fundamentals of classes data abstraction data encapsulation Data abstraction:

More information

COMP 356 Programming Language Structures Notes for Chapter 5 of Concepts of Programming Languages Names, Types and Scopes

COMP 356 Programming Language Structures Notes for Chapter 5 of Concepts of Programming Languages Names, Types and Scopes Some definitions: COMP 356 Programming Language Structures Notes for Chapter 5 of Concepts of Programming Languages Names, Types and Scopes a name is a string of characters (a word) that represents a program

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

TDDB89 Advanced Programming in C++ Exercise Smart pointers

TDDB89 Advanced Programming in C++ Exercise Smart pointers TDDB89 Advanced Programming in C++ Exercise Smart pointers In this exercise you shall, given a simple class definition for a smart pointer type, first implement the given member functions and then successively

More information

Introduction to STL (Standard Template Library)

Introduction to STL (Standard Template Library) Introduction to STL (Standard Template Library) Rajanikanth Jammalamadaka A template is defined as something that establishes or serves as a pattern Websters In C++, a template

More information

Expert C Programming. Deep C Secrets. Peter van der Linden. SunSoft Press A Prentice Hall Title

Expert C Programming. Deep C Secrets. Peter van der Linden. SunSoft Press A Prentice Hall Title Expert C Programming Deep C Secrets Peter van der Linden SunSoft Press A Prentice Hall Title Contents Preface Xiii Acknowledgments xv Introduction xix The $20 Million Bug xx Converdi on xxi Some Light

More information

Classes and Structs in C++ Based on materials by Bjarne Stroustrup

Classes and Structs in C++ Based on materials by Bjarne Stroustrup Classes and Structs in C++ Based on materials by Bjarne Stroustrup www.stroustrup.com/programming Overview Classes Implementation and interface Constructors Member functions Enumerations Operator overloading

More information

CSCI-1200 Data Structures Fall 2015 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2015 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2015 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

Q1. For the following grammar: S a S b c E E d f E a

Q1. For the following grammar: S a S b c E E d f E a Chapter 3 (3.1 3.3) Describing Syntax and Semantics Chapter 4 Lexical and Syntax Analysis Chapter 5 Names, Binding, Type Checking and Scopes Chapter 6 Data Types Chapter 7 Expressions and Assignment Statements

More information

Review: arrays, pointers, structures (Chapter 1) Data Types. Review: Arrays. Data Types (C/C++) Data Type: CS 3358 Summer I 2012.

Review: arrays, pointers, structures (Chapter 1) Data Types. Review: Arrays. Data Types (C/C++) Data Type: CS 3358 Summer I 2012. Review: arrays, pointers, structures (Chapter 1) Data Types Data Type: CS 3358 Summer I 2012 Jill Seaman set of values set of operations over those values example: Integer whole numbers, -32768 to 32767

More information

CS1020E: DATA STRUCTURES AND ALGORITHMS I

CS1020E: DATA STRUCTURES AND ALGORITHMS I CS1020E: DATA STRUCTURES AND ALGORITHMS I Tutorial 1 Basic C++, OOP Problem Solving (Week 3, starting 22 August 2016) 1. Evaluation Order (Note: You can use any other C++ code editor/compiler). Examine

More information

A modest STL tutorial

A modest STL tutorial A modest STL tutorial By Jak Kirman I am using a software tool called hyperlatex to create this document. The tutorial is also available in compressed postscript form. For those wanting to install a copy

More information

vector vec double # in # cl in ude tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector { Software Design (C++) 3. Resource management and exception safety (idioms and technicalities) Juha Vihavainen University of Helsinki Preview More on error handling and exceptions checking array indices

More information

05 Case Study: C Programming Language

05 Case Study: C Programming Language CS 2SC3 and SE 2S03 Fall 2009 05 Case Study: C Programming Language William M. Farmer Department of Computing and Software McMaster University 18 November 2009 The C Programming Language Developed by Dennis

More information

CS271: Data Structures. Binary Search Trees

CS271: Data Structures. Binary Search Trees CS271: Data Structures Binary Search Trees This project has three parts: an implementation of a binary search tree class, a testing plan, and an experiment in tree height. 1. PART 1 Implement a binary

More information

Quiz 3 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 3 S o l u t i o n s. Q1: C++ functions other than main are executed:

Quiz 3 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 3 S o l u t i o n s. Q1: C++ functions other than main are executed: Quiz 3 Solutions Q1: C++ functions other than main are executed: a. Before main executes. b. After main completes execution. c. When they are explicitly called by another function. d. Never. ANS c. When

More information

Helpful C++ Transitions. Systems Programming

Helpful C++ Transitions. Systems Programming Helpful C++ Transitions A Few Helpful Slides #ifndef Objects using Classes 2 Avoiding Duplicate Headers #ifndef PRODUCT_H #define PRODUCT_H #endif 3 A Node Class Class Node { public: Node (string s); private:

More information

Language Examples of ADT: C++

Language Examples of ADT: C++ Language Examples of ADT: C++ Based on C struct type and Simula 67 classes All of the class instances of a class share a single copy of the member functions Each instance of a class has its own copy of

More information

Quick Introduction to C++

Quick Introduction to C++ Quick Introduction to C++ Wayne A. Christopher handout for CS 162, UC Berkeley, 1992 (freely adapted by Riccardo Bettati ) C makes it easy to shoot yourself in the foot. C++ makes it harder, but when you

More information

C++ Support for Abstract Data Types

C++ Support for Abstract Data Types Topics C++ Support for Abstract Data Types Professor Department of EECS d.schmidt@vanderbilt.edu Vanderbilt University www.cs.wustl.edu/schmidt/ (615) 343-8197 Describing Objects Using ADTs Built-in vs.

More information

Abstract Data types Ivor Page 1

Abstract Data types Ivor Page 1 CS 3345 module 2, Abstract Data Types 1 Abstract Data types Ivor Page 1 2.1 Introduction An abstract data type (ADT) is a class specification that enables objects to be created at run time that (1) hold

More information

CS11 Introduction to C++ Spring Lecture 1

CS11 Introduction to C++ Spring Lecture 1 CS11 Introduction to C++ Spring 2011-2012 Lecture 1 Welcome! n Introduction to C++ Assumes general familiarity with C syntax and semantics n Loops, functions, pointers, memory allocation, structs, etc.

More information

Conversion Constructors

Conversion Constructors CS106L Winter 2007-2008 Handout #18 Wednesday, February 27 Conversion Constructors Introduction When designing classes, you might find that certain data types can logically be converted into objects of

More information

SOFTWARE ENGINEERING 2: OBJECT ORIENTED SOFTWARE ENGINEERING

SOFTWARE ENGINEERING 2: OBJECT ORIENTED SOFTWARE ENGINEERING SOFTWARE ENGINEERING 2: OBJECT ORIENTED SOFTWARE ENGINEERING 1. This is a general question about Object Oriented Software Engineering. a) Compare and contrast how software complexity is handled in Structured

More information

Summary. Pre requisition. Content Details: 1. Basics in C++

Summary. Pre requisition. Content Details: 1. Basics in C++ Summary C++ Language is one of the approaches to provide object-oriented functionality with C like syntax. C++ adds greater typing strength, scoping and other tools useful in object-oriented programming

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

CS 246 Winter 2016 Assignment 3 Instructors: Peter Buhr and Rob Schluntz Due Date: Monday, March 7, 2016 at 22:00

CS 246 Winter 2016 Assignment 3 Instructors: Peter Buhr and Rob Schluntz Due Date: Monday, March 7, 2016 at 22:00 CS 246 Winter 2016 Assignment 3 Instructors: Peter Buhr and Rob Schluntz Due Date: Monday, March 7, 2016 at 22:00 March 1, 2016 This assignment examines intermediate-level C++ and classes. Use it to become

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

Programming Languages

Programming Languages Programming Languages Memory Allocation & Garbage Collection CSCI.GA-2110-003 Fall 2011 Dynamic memory management For most languages, the amount of memory used by a program cannot be determined at compile

More information

Which of the following is the correct operator to compare two variables? A. := B. = C. equal D. ==

Which of the following is the correct operator to compare two variables? A. := B. = C. equal D. == Group 1 Question 1. What is the correct value to return to the operating system upon the successful completion of a program? A. -1 B. 1 C. 0 D. Programs do not return a value. Question 2. What is the only

More information

Chapter 13. Pointers and Linked Lists

Chapter 13. Pointers and Linked Lists Chapter 13 Pointers and Linked Lists Overview 13.1 Nodes and Linked Lists 13.2 Stacks and Queues Slide 13-2 13.1 Nodes and Linked Lists Nodes and Linked Lists n A linked list is a list that can grow and

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Dan Grossman Spring 2005 Lecture 25 Memory-Management Idioms Dan Grossman CSE303 Spring 2005, Lecture 25 1 No tools or rule today Review: Java and C

More information

CSCI-1200 Data Structures Fall 2015 Lecture 18 Trees, Part I

CSCI-1200 Data Structures Fall 2015 Lecture 18 Trees, Part I Review from Lectures 17 CSCI-1200 Data Structures Fall 2015 Lecture 18 Trees, Part I Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

C++ for Safety-Critical Systems

C++ for Safety-Critical Systems C++ for Safety-Critical Systems Günter Obiltschnig Applied Informatics Software Engineering GmbH St. Peter 33 9184 St. Jakob im Rosental Austria guenter.obiltschnig@appinf.com Abstract. C++ is now widely

More information

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= Much of the surrounding prose written by Andy Maag, CS193D instructor from years ago. The compiler will supply a default (zero-argument)

More information

Introduction to C++ Programming

Introduction to C++ Programming Introduction to C++ Programming C++ is one of the most popular programming languages in use in industry today. According to the TIOBE Programming Community Index, which can be accessed at this url: http://www.tiobe.com/index.php/content/paperinfo/tpci/

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

Bhakta Kavi Narsinh Mehta University, Junagadh

Bhakta Kavi Narsinh Mehta University, Junagadh Bhakta Kavi Narsinh Mehta University, Junagadh Draft Syllabus for B.Sc. (Computer Science) Bachelor of Science (Computer Science) (Semester - 1) Effective From June - 2016 B.Sc. (C.S.) (Semester - 1) CS-101:

More information

CS 230 Programming Languages

CS 230 Programming Languages CS 230 Programming Languages 11 / 30 / 2015 Instructor: Michael Eckmann Questions/comments? Today s Topics Chapter 6 Pointers Dangling pointer problem Memory leaks Solutions Michael Eckmann - Skidmore

More information

CSE 303 Concepts and Tools for Software Development. Magdalena Balazinska Winter 2010 Lecture 19 Inheritance (virtual functions and abstract classes)

CSE 303 Concepts and Tools for Software Development. Magdalena Balazinska Winter 2010 Lecture 19 Inheritance (virtual functions and abstract classes) CSE 303 Concepts and Tools for Software Development Magdalena Balazinska Winter 2010 Lecture 19 Inheritance (virtual functions and abstract classes) Where We Are We have already covered the introduction

More information

Coding conventions and C++-style

Coding conventions and C++-style Chapter 1 Coding conventions and C++-style This document provides an overview of the general coding conventions that are used throughout oomph-lib. Knowledge of these conventions will greatly facilitate

More information

C++ dlopen mini HOWTO

C++ dlopen mini HOWTO C++ dlopen mini HOWTO Aaron Isotton 2006 03 16 Revision History Revision 1.10 2006 03 16 Revised by: AI Changed the license from the GFDL to the GPL. Fixed usage of dlerror; thanks

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

Introduction to C++ Inheritance Topic #3

Introduction to C++ Inheritance Topic #3 Introduction to C++ Inheritance Topic #3 CS202 3-1 Topic #3 CS202 3-2 Single Inheritance Introduction to Inheritance "Using" versus "Containing" Relationships "Containing" Relationships...through inheritance

More information

(The Preprocessor) 5. C Syntax III: The Preprocessor 5-1

(The Preprocessor) 5. C Syntax III: The Preprocessor 5-1 5. C Syntax III: The Preprocessor 5-1 Chapter 5: C Syntax III (The Preprocessor) References: Brian W. Kernighan / Dennis M. Ritchie: The C Programming Language, 2nd Ed. Prentice-Hall, 1988. Samuel P. Harbison

More information

2. Names, Scopes, and Bindings

2. Names, Scopes, and Bindings 2. Names, Scopes, and Bindings Binding, Lifetime, Static Scope, Encapsulation and Modules, Dynamic Scope Copyright 2010 by John S. Mallozzi Names Variables Bindings Binding time Language design issues

More information

MAFS 5240 C++ Basics Arrays & Pointers

MAFS 5240 C++ Basics Arrays & Pointers MAFS 5240 C++ Basics Arrays & Pointers Arrays Pointers 1 Arrays holds a collection of objects of some type arrays are fixed size; new elements cannot be added individual objects are not named; each one

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

CISC 181 Project 3 Designing Classes for Bank Accounts

CISC 181 Project 3 Designing Classes for Bank Accounts CISC 181 Project 3 Designing Classes for Bank Accounts Code Due: On or before 12 Midnight, Monday, Dec 8; hardcopy due at beginning of lecture, Tues, Dec 9 What You Need to Know This project is based on

More information

C++ Introduction to class and data abstraction

C++ Introduction to class and data abstraction C++ Introduction to class and data abstraction 1 Data abstraction A data abstraction is a simplified view of an object by specifying what can be done with the object while hiding unnecessary details In

More information

CS11 Introduction to C++ Winter Lecture 8

CS11 Introduction to C++ Winter Lecture 8 CS11 Introduction to C++ Winter 2011-2012 Lecture 8 Local Variables string getusername() { string user; } cout user; return user; n What happens to user when function

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Lecture 5. Function Pointers

Lecture 5. Function Pointers Lecture 5 Complicated declarations Pointers to functions Templates Classes const member functions Constructors and destructor Allocating and deallocating memory Common pitfalls TNCG18 (C++): Lec 5 1 Function

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Fall 2007 7p-9p, Thursday, October 4 Name: NetID: Lab Section

More information

C Primer. Fall Introduction C vs. Java... 1

C Primer. Fall Introduction C vs. Java... 1 CS 33 Intro Computer Systems Doeppner C Primer Fall 2016 Contents 1 Introduction 1 1.1 C vs. Java.......................................... 1 2 Functions 1 2.1 The main() Function....................................

More information

SYSTEMS PROGRAMMING C++ INTRODUCTION

SYSTEMS PROGRAMMING C++ INTRODUCTION Faculty of Computer Science / Institute of Systems Architecture / Operating Systems SYSTEMS PROGRAMMING C++ INTRODUCTION Alexander Warg WHY C++? C++ is the language that allows to express ideas from the

More information

Functions. Recursion

Functions. Recursion CandC++ 2. Functions Preprocessor Stephen Clark University of Cambridge (heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford and Bjarne Stroustrup) Michaelmas Term 2011

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

Introduction to Java A First Look

Introduction to Java A First Look Introduction to Java A First Look Java is a second or third generation object language Integrates many of best features Smalltalk C++ Like Smalltalk Everything is an object Interpreted or just in time

More information

STL and new stuff in C++11

STL and new stuff in C++11 Michal misof Forišek Department of Theoretical Computer Science Faculty of Mathematics, Physics and Informatics Comenius University Bratislava, Slovakia February 2012 STL: Intro Standard Template Library

More information

1. Polymorphism in C++...2

1. Polymorphism in C++...2 1. Polymorphism in C++...2 1.1 Polymorphism and virtual functions... 2 1.2 Function call binding... 3 1.3 Virtual functions... 4 1.4 How C++ implements late binding... 6 1.4.1 Why do I have to know at

More information

6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011 6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

More information

Object Oriented Programming V Fall Final Exam SOLUTION

Object Oriented Programming V Fall Final Exam SOLUTION Object Oriented Programming V22.0470 Fall 2000 Final Exam SOLUTION Write the answers to question 1 and 2 on this sheet. Write the other answers in the exam booklet. There are four pages to this exam! 1.

More information

Java Memory Management

Java Memory Management Java Memory Management 1 Tracing program execution Trace: To follow the course or trail of. When you need to find and fix a bug or have to understand a tricky piece of code that your coworker wrote, you

More information