Constructors and Assignment. Mike Precup
|
|
- Frank Owen
- 7 years ago
- Views:
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!
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 informationA 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 informationObject 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 informationStorage 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 informationCpSc212 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 informationAn 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 informationC++ 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 informationCopyright 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 informationCS193D 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 informationIntroduction 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 informationPART-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 informationCS107L 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 informationConversion 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 informationThe 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 information1 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 informationC++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 informationOperator 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 informationName: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
More informationC++ 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 informationObject 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 informationvector 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 informationComp151. 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 informationCS107L 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 informationCalling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?
Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function
More information1. 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 informationThe Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25
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 informationKITES TECHNOLOGY COURSE MODULE (C, C++, DS)
KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL
More informationIS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction
IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points
More information13 Classes & Objects with Constructors/Destructors
13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.
More informationCoding 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 informationBoolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
More informationCS11 Advanced C++ Spring 2008-2009 Lecture 9 (!!!)
CS11 Advanced C++ Spring 2008-2009 Lecture 9 (!!!) The static Keyword C++ provides the static keyword Also in C, with slightly different usage Used in two main contexts: Declaring static members of a class
More informationCommon Data Structures
Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees
More informationCISC 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 informationC++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 informationFor 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 informationC++ 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 informationNote: Syntactically, a ; is needed at the end of a struct definition.
Structs, Classes, and Arrays Structs A type representation containing a set of heterogeneous members with possibly varying types. struct Student { string name; int id; double tuition; ; Note: Syntactically,
More informationChapter One Introduction to Programming
Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of
More informationIn order to understand Perl objects, you first need to understand references in Perl. See perlref for details.
NAME DESCRIPTION perlobj - Perl object reference This document provides a reference for Perl's object orientation features. If you're looking for an introduction to object-oriented programming in Perl,
More informationBasic Object-Oriented Programming in Java
core programming Basic Object-Oriented Programming in Java 1 2001-2003 Marty Hall, Larry Brown http:// Agenda Similarities and differences between Java and C++ Object-oriented nomenclature and conventions
More informationCIS 190: C/C++ Programming. Polymorphism
CIS 190: C/C++ Programming Polymorphism Outline Review of Inheritance Polymorphism Car Example Virtual Functions Virtual Function Types Virtual Table Pointers Virtual Constructors/Destructors Review of
More informationLecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance
Introduction to C++ January 19, 2011 Massachusetts Institute of Technology 6.096 Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance We ve already seen how to define composite datatypes
More informationDemonstrating a DATA Step with and without a RETAIN Statement
1 The RETAIN Statement Introduction 1 Demonstrating a DATA Step with and without a RETAIN Statement 1 Generating Sequential SUBJECT Numbers Using a Retained Variable 7 Using a SUM Statement to Create SUBJECT
More informationEP241 Computer Programming
EP241 Computer Programming Topic 10 Basic Classes Department of Engineering Physics University of Gaziantep Course web page www.gantep.edu.tr/~bingul/ep241 Sep 2013 Sayfa 1 Introduction In this lecture
More informationObject Oriented Software Design II
Object Oriented Software Design II Real Application Design Christian Nastasi http://retis.sssup.it/~lipari http://retis.sssup.it/~chris/cpp Scuola Superiore Sant Anna Pisa April 25, 2012 C. Nastasi (Scuola
More informationPROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON
PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London
More informationMultichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is
Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations
More informationComputer Programming C++ Classes and Objects 15 th Lecture
Computer Programming C++ Classes and Objects 15 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2013 Eom, Hyeonsang All Rights Reserved Outline
More informationApplied Informatics C++ Coding Style Guide
C++ Coding Style Guide Rules and Recommendations Version 1.4 Purpose of This Document This document describes the C++ coding style employed by Applied Informatics. The document is targeted at developers
More informationHow To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)
TN203 Porting a Program to Dynamic C Introduction Dynamic C has a number of improvements and differences compared to many other C compiler systems. This application note gives instructions and suggestions
More informationMoving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
More informationCS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team
CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A
More informationSemantic Analysis: Types and Type Checking
Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors
More informationLet s start with a simple, object-oriented model of a point in two-dimensional space:
CS107L Handout 01 Autumn 2007 September 28, 2007 Constructors and Destructors point class Let s start with a simple, object-oriented model of a point in two-dimensional space: class point public: point(double
More informationGoals for This Lecture:
Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value
More informationINTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011
INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE
More informationJava Interview Questions and Answers
1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java
More informationIntroduction to Data Structures
Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate
More informationC++ Crash Kurs. C++ Object-Oriented Programming
C++ Crash Kurs C++ Object-Oriented Programming Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ classes A class is user-defined type
More informationIntroduction to Programming Block Tutorial C/C++
Michael Bader Master s Program Computational Science and Engineering C/C++ Tutorial Overview From Maple to C Variables, Operators, Statements Functions: declaration, definition, parameters Arrays and Pointers
More informationData Structures Using C++ 2E. Chapter 5 Linked Lists
Data Structures Using C++ 2E Chapter 5 Linked Lists Test #1 Next Thursday During Class Cover through (near?) end of Chapter 5 Objectives Learn about linked lists Become aware of the basic properties of
More informationIntroduction to Objective-C. Kevin Cathey
Introduction to Objective-C Kevin Cathey Introduction to Objective-C What are object-oriented systems? What is the Objective-C language? What are objects? How do you create classes in Objective-C? acm.uiuc.edu/macwarriors/devphone
More informationJava from a C perspective. Plan
Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,
More informationexplicit class and default definitions revision of SC22/WG21/N1582 = 04-0022 and SC22/WG21/ N1702 04-0142
Doc No: SC22/WG21/ N1717 04-0157 Project: Programming Language C++ Date: Friday, November 5, 2004 Author: Francis Glassborow & Lois Goldthwaite email: francis@robinton.demon.co.uk explicit class and default
More informationClass 16: Function Parameters and Polymorphism
Class 16: Function Parameters and Polymorphism SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 16 Fall 2011 1 / 15
More informationVieta s Formulas and the Identity Theorem
Vieta s Formulas and the Identity Theorem This worksheet will work through the material from our class on 3/21/2013 with some examples that should help you with the homework The topic of our discussion
More informationCS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5
This Week CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5 School of Computer Science University of St Andrews Graham Kirby Alan Dearle More on Java classes Constructors Modifiers cdn.videogum.com/img/thumbnails/photos/commenter.jpg
More informationSoftware Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009
Software Engineering Concepts: Testing Simple Class Example continued Pointers & Dynamic Allocation CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Glenn G. Chappell Department
More informationSemantic Checker (Part I)
Semantic Checker (Part I) Now, the coding (and the fun) begins. Your Parser fix: parser integration main statements i/o statments don't worry about: error recovery (possibly stripping those rules out)
More informationN3458: Simple Database Integration in C++11
N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,
More informationNode-Based Structures Linked Lists: Implementation
Linked Lists: Implementation CS 311 Data Structures and Algorithms Lecture Slides Monday, March 30, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org
More informationSources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
More informationConstructor, Destructor, Accessibility and Virtual Functions
Constructor, Destructor, Accessibility and Virtual Functions 182.132 VL Objektorientierte Programmierung Raimund Kirner Mitwirkung an Folienerstellung: Astrit Ademaj Agenda Constructor Destructors this
More information3 Representation in C++.
3 Representation in C++. The computer language C++ is well suited for implementing a grid generator. C++ is a superset of C. The discussion below assumes knowledge of the language C. One major difference
More informationPointers and Linked Lists
15 Pointers and Linked Lists 15.1 Nodes and Linked Lists 828 Nodes 828 Linked Lists 834 Inserting a Node at the Head of a List 835 Pitfall:Losing Nodes 839 Searching a Linked List 840 Pointers as Iterators
More informationIntegrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum
Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum James P. Kelsh James.Kelsh@cmich.edu Roger Y. Lee lee@cps.cmich.edu Department of Computer Science Central
More information1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.
1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated
More informationPolymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism
Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)
More informationPolynomial Invariants
Polynomial Invariants Dylan Wilson October 9, 2014 (1) Today we will be interested in the following Question 1.1. What are all the possible polynomials in two variables f(x, y) such that f(x, y) = f(y,
More informationA Comparison of Programming Languages for Graphical User Interface Programming
University of Tennessee, Knoxville Trace: Tennessee Research and Creative Exchange University of Tennessee Honors Thesis Projects University of Tennessee Honors Program 4-2002 A Comparison of Programming
More informationwww.sahajsolns.com Chapter 4 OOPS WITH C++ Sahaj Computer Solutions
Chapter 4 OOPS WITH C++ Sahaj Computer Solutions 1 Session Objectives Classes and Objects Class Declaration Class Members Data Constructors Destructors Member Functions Class Member Visibility Private,
More informationVisual C++ 2010 Tutorial
Visual C++ 2010 Tutorial Fall, 2011 Table of Contents Page No Introduction ------------------------------------------------------------------- 2 Single file program demo --------- -----------------------------------------
More informationPreparing and Revising for your GCSE Exams
Preparing and Revising for your GCSE Exams Preparing and Revising for GCSEs Page 2 Contents Introduction 3 Effective Learning and Revision 4 What you need to Revise 5 Revision Notes and Practice 6 Getting
More informationThe Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1
The Java Series Java Essentials I What is Java? Basic Language Constructs Slide 1 What is Java? A general purpose Object Oriented programming language. Created by Sun Microsystems. It s a general purpose
More informationStatic vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer
Lecture 10: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis
More information1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {
Operators C and C++ 6. Operators Inheritance Virtual Alastair R. Beresford University of Cambridge Lent Term 2008 C++ allows the programmer to overload the built-in operators For example, a new test for
More informationBrent A. Perdue. July 15, 2009
Title Page Object-Oriented Programming, Writing Classes, and Creating Libraries and Applications Brent A. Perdue ROOT @ TUNL July 15, 2009 B. A. Perdue (TUNL) OOP, Classes, Libraries, Applications July
More informationWhy you shouldn't use set (and what you should use instead) Matt Austern
Why you shouldn't use set (and what you should use instead) Matt Austern Everything in the standard C++ library is there for a reason, but it isn't always obvious what that reason is. The standard isn't
More informationCours de C++ Utilisations des conteneurs
Cours de C++ Utilisations des conteneurs Cécile Braunstein cecile.braunstein@lip6.fr 1 / 18 Introduction Containers - Why? Help to solve messy problems Provide useful function and data structure Consistency
More informationChapter 5 Functions. Introducing Functions
Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name
More informationCMSC 202H. ArrayList, Multidimensional Arrays
CMSC 202H ArrayList, Multidimensional Arrays What s an Array List ArrayList is a class in the standard Java libraries that can hold any type of object an object that can grow and shrink while your program
More informationCurriculum Map. Discipline: Computer Science Course: C++
Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code
More informationarrays C Programming Language - Arrays
arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)
More informationFriendship and Encapsulation in C++
Friendship and Encapsulation in C++ Adrian P Robson Department of Computing University of Northumbria at Newcastle 23rd October 1995 Abstract There is much confusion and debate about friendship and encapsulation
More informationClasses and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:
In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our
More informationMore C++ Concepts. Operator overloading Friend Function This Operator Inline Function
More C++ Concepts Operator overloading Friend Function This Operator Inline Function 1 Review There are different types of member functions in the definition of a class Accessor int Str :: get_length();
More informationInline Variables. Document Number: N4424 Date: 2015 04 07 Hal Finkel (hfinkel@anl.gov) and Richard Smith (richard@metafoo.co.
Document Number: N4424 Date: 2015 04 07 Hal Finkel (hfinkel@anl.gov) and Richard Smith (richard@metafoo.co.uk) Inline Variables Introduction C++ generally requires all extern functions and variables to
More informationpublic static void main(string[] args) { System.out.println("hello, world"); } }
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More information