2 ADT Programming User-defined abstract data types

Size: px
Start display at page:

Download "2 ADT Programming User-defined abstract data types"

Transcription

1 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 for data members copy construction and assignment of objects canonical class form and guidelines for safe construction on overloading of operators (+, -, *, /, << ) 1 2 ADT programming "object-based" programming unlike object-oriented programming does not use derived classes (subclasses) B. Stroustrup speaks of ADT (Abstract Data Type) programming for many situations, ADTs are a sufficient and recommendable solution - without using objectoriented mechanisms (inheritance, run-time binding) for example, STL (Standard Template Library) doesn't use subtyping, nor has any need for an Object root class object-oriented programming techniques enable building application frameworks (discussed later) generic programming enables reuse and code generation by static code templates (discussed later) 3 Basic class terminology object fields are called data members object methods or operations are member functions (!) also have class-level members (defined as static) the set of all public features is called a public interface, or simply interface (not a keyword in C++) the term "attribute" or "property" should be reserved for modeling - not necessarily data fields but may be logical attributes that are implemented by special modifier and accessor functions (e.g., "size" attribute of a container) 4 Class a class definition contains the definitions of data members but it does not (usually) contain the definitions of operations, only their declarations class definitions are (usually) stored in header files definitions of operations are provided outside of the class definition, stored in a source file (.cpp) members can be referred to using the general scope operator ::, often in the full from NamespaceName::ClassName::memberName sections consisting of one or more declarations, are tagged with visibility specifications: public, protected, or private 5 // student.h explicit Student (long); // constructor // operation // private field ; // note the semicolon // student.cpp #include "student.h" // get definitions Student::Student (long number) { // constructor number_= number; void Student::setNumber (long number) { // operation number_= number; 6 1

2 Errors: class syntax remember to use scope operator :: void setnumber (long number) { // error: global void Student::setNumber (long number) { // OK data members cannot be initialized in the class declaration (usually): long number_= 2; // error: illegal construct in C++ // initialize in a ctor ; class definitions are terminated with a semicolon 7 Recommended style explicit Student (long); long getnumber () const; ; //..cpp file // modifier/mutator // query/accessor/ // inspector Query specification Repeated in definition long Student::getNumber () const { return number_; the right format and conventions contribute towards program readability and reliability 8 Why accessors? only const operations may be invoked for objects that are declared or accessed as const Student const*stud = new Student (9); stud->setnumber (10); // error: can't change improves readability and safety, and the compiler can help to protect data and to catch mistakes long Student::getNumber () const { number_+= 100; // error: can't change return number_; const operations can invoke other member functions only if those are also const if you change your code and make an operation const, this may have a ripple effect of having to make other operations const, too (but beneficial) 9 inline functions inline long Student::getNumber () const { return number_; ; accessors can be defined inline to avoid call overheads preserves valid semantics of a function call inline is interpreted as a hint for the compiler since inline functions are (usually) expanded at place, definitions of these functions must be put in header files the same needed for templates, see later class member functions that are defined within the class definition (Java-like) are considered (implicitly) inline but not recommended C++ style 10 Constructors explicit Student (long); long getnumber () const; ; // constructor Student s (10); // stack-allocated object Student * sp = new Student (11); // heap object Student * const sp1 = new Student (12); // const pointer but in Java: Student s = new Student (10); // always a reference 11 Constructors (cont.) a constructor transforms a region of memory to a valid object, initializing its data members, reserving resources, establishing invariants, etc. whenastudent variable is declared, memory for it is allocated on the stack, and then the appropriate constructor is invoked: Student student (100); // declared object or Student student = Student (100); // uses temp (but silly) the operator new: (1) allocates memory on the heap, and (2) calls the constructor; for example Student*michael = new Student (100); // from heap 12 2

3 Constructors (cont.) constructors can be overloaded and may have default arguments (at the end of the parameter list) a constructor that does not require any actual arguments (may have default ones) is called a default constructor (also: "zero-arguments constructor") if you do not define any constructors, C++ implicitly generates a default constructor that calls the default constructors for all data members of class type compile-time error if no such default constructors but does not perform initialization of primitive data members: numbers, pointers, etc. usually best to define the default constructor yourself must be unique (compiler checks: "ambiguous call") 13 Member initializer list Student (long no, std::string const& name = ""); // not initialized here (no default) std::string name_; // not initialized here (but ctor) ; void Student::Student (long no, std::string const& name) : number_(no), name_(name) // comma-separated list { // empty block body 14 Initialization of data members the initializers should be listed in the declaration order since the execution always proceeds in that order class A { explicit A (int s); // prevent type conversion int i_; int k_; ; A::A (int s) : k_(s), i_(k_) { // wrong order => error members will be destructed in reverse order all constructors use the same order (one destructor only) avoid unnecessarily using other data members in the initializer expressions 15 Idioms: Initialization of members the member initializer list is recommended and often obligatory; must initialize at least the following members (and always in the order of their declarations): const members (since cannot be changed later) references (since must be bound to an object) data members of class types - to omit overhead of a compiler-generated extra default initialization X::X () { mbr_= Y (1, 2); // init and assign here! // compiler generates: X::X () : mbr_() { mbr_=.. Y mbr_; base class part, calling a constructor with arguments but always avoid (unmanaged) new in member initializer lists (discussed later with exception safety) 16 Destructor internal clean-up and release actions should be invoked every time an object is destroyed C++ provides the destructor to manage resources explicit Student (long); // acquire resources long getnumber () const; ~Student (); // release resources SomeResource r_; // whatever.. ; 17 Destructor (cont.) cannot be overloaded: only one way to destruct an object is not allowed to have any parameters: normally called implicitly by the compiler (exit from block, exceptions) releases resources in reverse order as compared to constructors cannot be specified as const (of course) if you do not provide a destructor, the compiler generates some default one - possibly with an empty body consider void foo(long number) { Student student (number); // declared local object return; // calls Student::~Student () 18 3

4 Destructor (cont.) destructors release resources when an object having these resources is destroyed, e.g., goes out of scope (at block or function exit), is deallocated using the delete operation, is a global object removed at the end of program (after exiting from main), or when an exception propagates back the call chain and destructors of locals are called by the run-time system the delete operation first calls the destructor of the corresponding class, and then deallocates memory at block exit, destructors are not automatically called for objects created via new (of course) so-called handle objects or smart pointers may be used to automate destruction (discussed later) 19 Copying objects consider two variables x and y, and copying values between them: C x, y; // declare two objects of C: uses default ctor (1) the copying of values between two objects x = y; // uses assignment operator = (2) an initialization of a new object using an existing object C x = y; C*p = new C (y); // uses copy constructor // uses copy constructor by default, every class provides an assignment and a copy constructor these use shallow memberwise copying of data members (e.g., addresses specified as pointers are copied and shared) 20 Copy constructor a copy constructor uses a const pass-by-reference: C (C const& rhs); // cannot use value parameter! defines semantics for (1) value parameters and (2) return values (1) when a parameter of a class type is passed by value: the formal parameter is a new local object (variable) copy-constructed from the actual argument (2) when a value of a class type is returned by a function x = y + foo (); // calling function foo the return value from foo () is copy-constructed to a temporary used in the expression (then destructed) the compiler may sometimes optimize away unnecessary temporaries and copying operations 21 Construction guidelines data members are nested objects that are maintained by the C++ run-time system created when the surrounding object is created, destroyed when the surrounding object is destroyed often, we need explicit control over the resources of an object, and ownerships are established algorithmically when using pointer members, we define special versions of the four operations, in so-called canonical class form (1) default constructor, e.g., X::X (T = 0) (2) copy constructor X::X (X const&) (3) assignment X::operator = (X const&) (4) destructor X::~X ( ) 22 explicit Student (long); ; class StudInfo { explicit StudInfo (long); long number () const; // silly but illustrative // special constructor // query StudInfo (); // (1) default ctor StudInfo (StudInfo const&); // (2) copy ctor StudInfo& operator = (StudInfo const&); // (3) assignment ~StudInfo (); // (4) destructor Student * rep_; // dynamic resource ; 23 Construction guidelines (cont.) the default constructor should initialize primitive fields - especially set pointers to zero, and then create/allocate resources to set up a valid state and establish invariants the copy constructor should initialize all primitive fields, and copy every required element the assignment operator ("lhs = rhs") should (1) build/copy resources from the rhs (may fail & throw), (2) release old resources from lhs, and finally (3) establish the final state in a safe manner, e.g., by assigning a pointer to the built new state the destructor should release all resources resetting released pointers to a detectable invalid value enables checks for dangling references (usually during debugging/testing) 24 4

5 Safe construction StudInfo& StudInfo::operator = (StudInfo const& rhs) { if (this == &rhs) // check self-assign return *this; // nothing to assign Student * tmp=new Student (*rhs.rep_); // may fail (1) delete rep_; // release resource maintained by lhs (2) rep_= tmp; // assign new state safely: no fail (3) return*this; // comply with built-in assignment StudInfo::StudInfo (StudInfo const& rhs) { rep_= new Student (*rhs.rep_); StudInfo::StudInfo (long number) { rep_= new Student (number); StudInfo::~StudInfo () { delete rep_; rep_= 0; // or: rep_= INVPTR_VAL; Notes on safe construction in the assignment, the object is changed only after the creation & copying are already done and both succeeded => if a failure occurs, no changes, class invariants hold, and so the object can, e.g., be destructed later note that "new Student (*rhs.rep_)" calls on the copy constructor of the object (*rep_); such recursive copying or deletion is common (but the programmer controls) for debugging, the destructor may assign a detectable invalid pointer value e.g., the pattern 0xdddddddd - "d" for "dead" - is used by Microsoft's compilers to mark freed heap memory real-world examples with dynamic resources std::string, std::vector, etc Overloaded operators 1. All C++ operators can be overloaded, with the exception of some special "operators" (:: sizeof..*?: ) 2. When an operator is overloaded, its precedence and associativity do not change; neither can you invent and add any new operator symbols. 3. Overloaded operators are functions and not assumed to have extra arithmetic properties (e.g., commutative), so no modifications (or optimizations) apply. 4. To overload an operator, such as +, declare a function whose name is "operator +" T operator + (T lhs, T rhs); // function signature 5. Operator functions can be either member functions or separately defined (helper) functions. Overloaded operators (cont.) 6. The expressions+=, -=, ++ and-- are not automatically interpreted as of some sort of "shorthand" (they are all independent functions); for example Array v, w; // hypothetical user-defined type v = v + w;... // assume Array overloads + v += w; // error, unless Array also supports += 7. If not defined, default constructor, copy constructor, destructor, assignment (=), address of (&), and comma operator (,) are always generated by the compiler. the default implementation of the copy constructor and the assignment is shallow memberwise copy Overloading arithmetic operators class Integer { // illustrative number class Integer (int = 0); // no explicit: defines type conversion int get () const; // query operation Integer& operator += (Integer const&); // i += anint Integer& operator += (int); // i += 3 int value_; ; // some stand-alone functions (helpers) Integer operator + (Integer const&, Integer const&); Integer operator + (Integer const&, int); 29 Overloading arithmetics (cont.) Integer& Integer::operator += (Integer const& rhs) { value_+= rhs.value_; return *this; // implementation of helper functions Integer operator + (Integer const& i1, Integer const& i2) { return Integer (i1) += i2; // operator += (Integer const&) Integer operator + (Integer const& i, int v) { return Integer (i) += v; // operator += (int) // overloads are often defined as inline for efficiency 30 5

6 Integer i, k; ++i; k = i++; // using autoincrements class Integer { // preserve natural semantics Integer& operator ++ (); // prefix ++i Integer operator ++ (int); // postfix i++ // note the different return types int value_; ; Integer& Integer::operator ++ () { // prefix form ++value_; // modify and return *this; // then return new value Integer Integer::operator ++ (int) { // postfix form // parameter is not used Integer old (value_); // make copy of old value ++value_; // modify and then return old; // return old value 31 // integer.h Overloading IO operations #include <iosfwd> // forward declarations for iostreams std::ostream& operator << (std::ostream&, Integer const&); std::istream& operator >> (std::istream&, Integer&); // integer.cpp #include <iostream> // get iostream definitions using std::ostream; using std::istream; ostream& operator << (ostream& os, Integer const& i) { return os << i.get (); istream& operator >> (istream& is, Integer& i) { int val; if (is >> val) i = val; return is; 32 Idioms: overloaded operations 1. Operator functions that are modifiers are defined as members. Binary operators that return calculated object values are usually defined as separate helper functions. 2. Helper functions should be specified as friends only if the interface does not provide the necessary accessors (or if they are not sufficiently efficient). 3. Helper functions should be stored together with the underlying class in the same namespace. 4. If you overload one element from the following four sets of operations, must also take care to overload the other elements of that same set ==!= < > <= >= + (binary) += ++ (pre & post) + (unary, rarely used) - (binary) -= -- (pre & post) - (unary) 33 classes or helper functions specified as friends are logically a part of a class interface and implementation, and have the same access rights as member operations an example: List and its Java-style Iterator class Iterator; Friends // forward declaration class List { Iterator iterator (); // Java-style here friend class Iterator; // access to implementation ; for (Iterator it = list.iterator (); it.more (); ++it) cout << it.value () << endl; STL uses pointer-like iterators ("it!= end ()") 34 Friends (cont.) friendship is not transitive: friends of friends have no special privileges friendship is not symmetric: if Y is a friend of X then X is not automatically a friend of Y a derived class of X is not (by default) considered to be a friend friends cannot be declared for an already existing class: only the class itself can declare its friends friends do not necessarily break data hiding but can be used to support it you must sometimes grant special rights, e.g., consider iterators for containers alternative to friends would be to indiscriminately grant access to all 35 Classes: Guidelines 1. Classes should be named according to what they represent. 2. The three visibility sections are listed in the following order: public, protected, and private. 3. Every query method (accessor, inspector) is defined as a const function. 4. Use the canonical class form (with all four operations) for classes with dynamic resources. 5. Initialize data members in a member initializater list (but unmanaged new). 6. For private data members, use the suffix _. 36 6

7 Classes: Guidelines (cont.) 7. Header files contain class definitions, stand-alone function declarations, and definitions of constants; plus the documentation necessary to understand the semantics of this class by the client. 8. Definitions of member functions are placed in a separate file (but inline functions), which includes the header file containing the class definition. The comments and other documentation of the implementation of the class is placed in that source file. Summary constructors use an initializer list where data members are always placed in their declaration order primitive values (int) must always be explicitly initialized copy constructors and destructors are called by the runtime system (for parameters/return values/block exit) general guideline: make every resource, e.g., a heapallocated object, owned by some object const qualifiers can protect data from modifications const references are mostly used as read-only arguments to reduce unnecessary copying of (large) values friends get public access rights (given by the class itself) overloaded operations are specially named functions (without any arithmetic relations or transformations)

Ch. 12: Operator Overloading

Ch. 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 information

6 Architecture of C++ programs

6 Architecture of C++ programs 6 Architecture of C++ programs 1 Preview managing memory and other resources "resource acquisition is initialization" (RAII) using std::auto_ptr and other smart pointers safe construction of an object

More information

Short Notes of CS201

Short 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 information

CS201 - Introduction to Programming Glossary By

CS201 - 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 information

Absolute C++ Walter Savitch

Absolute 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 information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.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 information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

COMP6771 Advanced C++ Programming

COMP6771 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 information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 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 information

Introducing C++ to Java Programmers

Introducing 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 information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

explicit class and default definitions revision of SC22/WG21/N1582 =

explicit 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 information

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli Identify and overcome the difficulties encountered by students when learning how to program List and explain the software development roles played by students List and explain the phases of the tight spiral

More information

Fast Introduction to Object Oriented Programming and C++

Fast 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 information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. Welcome to Teach Yourself p. viii Acknowledgments p. xv Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. 6 Standard C++: A Programming Language and a Library p. 8

More information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. 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 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

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2 Steven J. Zeil November 13, 2013 Contents 1 Destructors 2 2 Copy Constructors 11 2.1 Where Do We Use a Copy Constructor? 12 2.2 Compiler-Generated Copy Constructors............................................

More information

Chapter 13: Copy Control. Overview. Overview. Overview

Chapter 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 information

CS3157: Advanced Programming. Outline

CS3157: 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 information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in

More information

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

More information

Object-Oriented Programming for Scientific Computing

Object-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 information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Midterm Review. PIC 10B Spring 2018

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 information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

CS 247: Software Engineering Principles. ADT Design

CS 247: Software Engineering Principles. ADT Design CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data

More information

Objects Managing a Resource

Objects Managing a Resource Objects Managing a Resource 1 What is a Resource Respects Release/Acquire protocol files (open/close) memory allocation (allocate/free) locks (acquire/release). 2 What is a Resource Objects when constructed,

More information

C++ Coding Standards. 101 Rules, Guidelines, and Best Practices. Herb Sutter Andrei Alexandrescu. Boston. 'Y.'YAddison-Wesley

C++ Coding Standards. 101 Rules, Guidelines, and Best Practices. Herb Sutter Andrei Alexandrescu. Boston. 'Y.'YAddison-Wesley C++ Coding Standards 101 Rules, Guidelines, and Best Practices Herb Sutter Andrei Alexandrescu 'Y.'YAddison-Wesley Boston Contents Prefaee xi Organizational and Poliey Issues 1 o. Don't sweat the small

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning

More information

Chapter 3. Object-Based Programming Part I

Chapter 3. Object-Based Programming Part I Chapter 3 Object-Based Programming Part I 3: Preview Object-based programming unlike object-oriented programming does not use extended (derived) classes. This chapter covers: similarities and differences

More information

ADTs in C++ In C++, member functions can be defined as part of a struct

ADTs 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 information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

More class design with C++ Starting Savitch Chap. 11

More class design with C++ Starting Savitch Chap. 11 More class design with C++ Starting Savitch Chap. 11 Member or non-member function? l Class operations are typically implemented as member functions Declared inside class definition Can directly access

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

CSC1322 Object-Oriented Programming Concepts

CSC1322 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

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

III. Classes (Chap. 3)

III. 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 information

G52CPP C++ Programming Lecture 13

G52CPP 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 information

Program construction in C++ for Scientific Computing

Program construction in C++ for Scientific Computing 1 (26) School of Engineering Sciences Program construction in C++ for Scientific Computing 2 (26) Outline 1 2 3 4 5 6 3 (26) Our Point class is a model for the vector space R 2. In this space, operations

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 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 information

Chapter 10 Introduction to Classes

Chapter 10 Introduction to Classes C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien DeAntoni adapted from Jean-Paul Rigault courses 1 2 This Week A little reminder Constructor / destructor Operator overloading

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

COMP6771 Advanced C++ Programming

COMP6771 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 information

Homework 4. Any questions?

Homework 4. Any questions? CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 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 information

G52CPP C++ Programming Lecture 20

G52CPP 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 information

COMP 2355 Introduction to Systems Programming

COMP 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 information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

And Even More and More C++ Fundamentals of Computer Science

And Even More and More C++ Fundamentals of Computer Science And Even More and More C++ Fundamentals of Computer Science Outline C++ Classes Special Members Friendship Classes are an expanded version of data structures (structs) Like structs, the hold data members

More information

Copy Control 2008/04/08. Programming Research Laboratory Seoul National University

Copy 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 information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Classes and Objects. Class scope: - private members are only accessible by the class methods. Class Declaration Classes and Objects class class-tag //data members & function members ; Information hiding in C++: Private Used to hide class member data and methods (implementation details). Public

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

More information

Chapter 5. Object- Oriented Programming Part I

Chapter 5. Object- Oriented Programming Part I Chapter 5 Object- Oriented Programming Part I 5: Preview basic terminology comparison of the Java and C++ approaches to polymorphic programming techniques introduced before in the context of inheritance:

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 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 information

Operator overloading. Conversions. friend. inline

Operator overloading. Conversions. friend. inline Operator overloading Conversions friend inline. Operator Overloading Operators like +, -, *, are actually methods, and can be overloaded. Syntactic sugar. What is it good for - 1 Natural usage. compare:

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

PIC 10A Objects/Classes

PIC 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 information

C How to Program, 6/e, 7/e

C How to Program, 6/e, 7/e C How to Program, 6/e, 7/e prepared by SENEM KUMOVA METİN modified by UFUK ÇELİKKAN and ILKER KORKMAZ The textbook s contents are also used 1992-2010 by Pearson Education, Inc. All Rights Reserved. Two

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Special Member Functions

Special Member Functions CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) U Waterloo CS247 (Spring 2017)

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

CGS 2405 Advanced Programming with C++ Course Justification

CGS 2405 Advanced Programming with C++ Course Justification Course Justification This course is the second C++ computer programming course in the Computer Science Associate in Arts degree program. This course is required for an Associate in Arts Computer Science

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

The Compositional C++ Language. Denition. Abstract. This document gives a concise denition of the syntax and semantics

The Compositional C++ Language. Denition. Abstract. This document gives a concise denition of the syntax and semantics The Compositional C++ Language Denition Peter Carlin Mani Chandy Carl Kesselman March 12, 1993 Revision 0.95 3/12/93, Comments welcome. Abstract This document gives a concise denition of the syntax and

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 12: Classes and Data Abstraction Objectives In this chapter, you will: Learn about classes Learn about private, protected,

More information

CPSC 427: Object-Oriented Programming

CPSC 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 information

04-19 Discussion Notes

04-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 information

Allocation & Efficiency Generic Containers Notes on Assignment 5

Allocation & Efficiency Generic Containers Notes on Assignment 5 Allocation & Efficiency Generic Containers Notes on Assignment 5 CS 311 Data Structures and Algorithms Lecture Slides Friday, October 30, 2009 Glenn G. Chappell Department of Computer Science University

More information

From 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++ 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 information

Plan of the day. Today design of two types of container classes templates friend nested classes. BABAR C++ Course 103 Paul F. Kunz

Plan of the day. Today design of two types of container classes templates friend nested classes. BABAR C++ Course 103 Paul F. Kunz Plan of the day Where are we at? session 1: basic language constructs session 2: pointers and functions session 3: basic class and operator overloading Today design of two types of container classes templates

More information