CSCI 123 Introduction to Programming Concepts in C++

Size: px
Start display at page:

Download "CSCI 123 Introduction to Programming Concepts in C++"

Transcription

1 CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe Brad Rippe More Classes and Dynamic Arrays

2 Overview 11.4 Classes and Dynamic Arrays Constructors, Destructors, Copy Constructors

3 Separation #include <iostream> // includes // declaration class MyDataType { Declaration public: double getmydt() const; void setmydt(double dt); private: double dt; }; int main() { // some instructions } // implementation void MyDataType::getMyDT() const { return this->dt } Implementation double MyDataType::setMyDT(double dt) { this->dt = dt; }

4 Separation of the interface from the implementation C++ provide a mechanism for separating the declaration from the implementation Implementation is the actual instructors for how the class operates. It determines how the function prototypes and constructor prototypes do their work Declaration (header) provides the prototypes for the class constructors and functions. It also declares any members of the class. The declaration is placed in a file with an h file extension The implementation (cpp) is placed in a file with a cpp file extension Both files should have the same file name, the name of the class Example: Bike.h and Bike.cpp

5 #include headers Assume we have a Bike.cpp and a Bike.h How do we include these files? What needs to happen? The #include < > statement is a preprocessor directive What did this instruction do?

6 #include headers Bike.h and Bike.cpp You must include the include the Bike.h in your main file. This will be a separate file from the Bike.h and the Bike.cpp This allows your main to be aware of the Bike class. Without the include, your main function doesn t understand what a Bike is. Likewise your Bike.cpp must include the Bike.h file so that it understand what a bike is

7 More Preprocessor Directives The preprocessor handles preprocessing directives, which can define and undefine macros, establish regions of conditional compilation, include other source files, and control the compilation process somewhat. A marco is a name that represents other text, called the macro replacement text When the macro name is seen in the source file, the preprocessor replaces the name with the replacement text Example #define ONE_HUNDRED 100

8 Preprocessor Directives #ifdef defines a conditional compilation region (if defined identifier) #ifdef BIKE_H #ifndef defines a conditional compilation region (if not defined identifier) #ifndef BIKE_H #endif terminates a conditional compilation region (end if)

9 Preprocessor Directives We can use the directives to ensure that the header file gets included once #ifndef BIKE_H //if the symbol is not defined #define BIKE_H // continue processing class Bike { public: }; #endif // Bike Declaration

10 Classes and Dynamic Arrays A dynamic array can have a class as its base type Bike *bikes = new Bike[25]; // 25 can be a variable A class can have a member variable that is a dynamic array In this section you will see a class using a dynamic array as a member variable.

11 Program Example: BikeStore We will define the class BikeStore BikeStore objects use dynamic arrays whose size is determined when the program is running We will redefine the class Bike

12 The BikeStore Constructors The default BikeStore constructor creates an object with a maximum array of 10 Another BikeStore constructor takes an argument of type int which determines the maximum array length of the object A third BikeStore constructor takes an array of bikes as an argument and the size sets maximum size of the bikes array to the size parameter copies the bikes from the parameter to the object s inventory

13 The BikeStore Interface In addition to constructors, the BikeStore interface includes: Member functions int getsize() const; int getcapacity() const; int resize(); friend ostream& operator << (ostream& out, const BikeStore& astore); Copy Constructor discussed later Destructor discussed later

14 A BikeStore Sample Program Using the BikeStore interface, we can write a program using the BikeStore class The program creates a Bike Store Adds two bikes to the store Outputs using the insertion operator from the BikeStore class and the Bike class

15 The BikeStore Implementation BikeStore uses a dynamic array to store its inventory BikeStore constructors call new to create the dynamic array for member variable minventory If msize == mcapacity, we resize our inventory for more bikes by doubling current capacity If mcapacity >= msize*2, we shrink the inventory Capacity and size determine at runtime

16 The BikeStore Implementation BikeStore members operator << addbike() removebike() movebikes() resize() shrink()

17 Dynamic Variables Dynamic variables do not "go away" unless delete is called Even if a local pointer variable goes away at the end of a function, the dynamic variable it pointed to remains unless delete is called A user of the BikeStore class could not know that a dynamic array is a member of the class, so would not be expected to call delete when finished with a BikeStore object

18 Destructors A destructor is a member function that is called automatically when an object of the class goes out of scope The destructor contains code to delete all dynamic variables created by the object A class has only one destructor with no arguments The name of the destructor is distinguished from the default constructor by the tilde symbol ~ Example: ~BikeStore( );

19 ~BikeStore The destructor in the BikeStore class must call delete [ ] to return the memory of any dynamic variables to the freestore Example: BikeStore::~BikeStore() { } delete [] minventory;

20 BikeStore Output Bike Store created... Bike store size is 0 Bike store capacity is 10 Adding bikes to the store Bike added successfully true Bike added successfully true Bike store size is 2 Bike store capacity is 10 Outputting Bike Store: Adding 10 bikes to the store Resize... Bike store size is 12 Bike store capacity is 20 Removing 10 bikes from the store Shrinking... Shrinking... Shrinking... Bike store size is 2 Bike store capacity is 2 Sample2 from destructors and constructors

21 Pointers as Call-by-Value Parameters Using pointers as call-by-value parameters yields results you might not expect Remember that parameters are local variables No change to the parameter should cause a change to the argument The value of the parameter is set to the value of the argument (an address is stored in a pointer variable) The argument and the parameter hold the same address If the parameter is used to change the value pointed to, this is the same value as the argument pointed to by the argument! BadPointerCopy.cpp

22 BadPointerCopy.cpp example What happened? BikeStore lastore; BikeStore ocstore; Bike truth("ellsworth Truth", 17, 26.0); Bike id("ellsworth Id", 19, 26.0); lastore.addbike(truth); lastore.addbike(id); ocstore = lastore; ocstore.removebike(truth); cout << "Orange County Store\n"; outputsizeandcapacity(ocstore); cout << ocstore; // Shrink() killed lastores pointer

23 Copy Constructors The problem with using call-by-value parameters with pointer variables is solved by the copy constructor. A copy constructor is a constructor with one parameter of the same type as the class The parameter is a call-by-reference parameter The parameter is usually a constant parameter The constructor creates a complete, independent copy of its argument

24 BikeStore Copy Constructor This code for the BikeStore copy constructor Creates a new dynamic array for a copy of the argument Making a new copy, protects the original from changes BikeStore::BikeStore(const BikeStore& abikestore) { } msize = abikestore.msize; mcapacity = abikestore.mcapacity; minventory = new Bike[mCapacity]; for(int i = 0; i < msize; i++) minventory[i] = abikestore.minventory[i]; CopyConstructor.cpp

25 Calling a Copy Constructor A copy constructor can be called as any other constructor when declaring an object The copy constructor is called automatically When a class object is defined and initialized by an object of the same class When a function returns a value of the class type When an argument of the class type is plugged in for a call-byvalue parameter

26 The Need For a Copy Constructor This code from BadPointerCopy.cpp ocstore = lastore; Causes the pointer in ocstore to point to the variables in lastore's inventory ocstore.minventory = lastore.minventory minventory is a pointer; we now have two pointers pointing at the same variable

27 The Need For a Copy Constructor (cont.) Since ocstore.minventory and lastore.minventory are pointers, they now point to the same dynamic array Ellsworth Truth Ellsworth Id ocstore.minventory lastore.minventory

28 The Need For a Copy Constructor (cont.) When ocstore resizes the inventory, it deletes the original array. This returns the dynamic array pointed to by lastore to the freestore Undefined ocstore.minventory lastore.minventory lastore.minventory now points to memory that has been given back to the freestore! While ocstore is reassigned

29 The Need For a Copy Constructor (cont.) Two problems now exist for object lastore Attempting to output lastore.minventory is likely to produce an error When lastore goes out of scope, its destructor will be called Calling a destructor for the same location twice is likely to produce a system crashing error

30 Copy Constructor Demonstration Using the same example, but with a copy constructor defined ocstore.minventory and lastore.minventory point to different locations in memory Ellsworth Truth Ellsworth Id Ellsworth Truth Ellsworth Id ocstore.minventory lastore.minventory

31 Copy Constructor Demonstration (cont.) When lastore goes out of scope, the destructor is called, returning lastore.minventoy to the freestore Ellsworth Truth Ellsworth Id undefined ocstore.minventory lastore.minventory ocstore.minventory still exists and can be accessed or deleted without problems

32 When To Include a Copy Constructor When a class definition involves pointers and dynamically allocated memory using "new ; include a copy constructor Classes that do not involve pointers and dynamically allocated memory do not need copy constructors

33 The Big Three The copy constructor The assignment operator The destructor If you need to define one, you need to define all

34 The Assignment Operator Given these declarations: BikeStore lastore; BikeStore ocstore; the statement ocstore = lastore; is legal But, since BikeStore's member value is a pointer, we have ocstore.minventory and lastore.minventory pointing to the same memory location

35 Overloading = The solution is to overload the assignment operator = so it works for BikeStore Remember the default operator copies members operator = is overloaded as a member function Example: operator = declaration void operator=(const BikeStore& abikestore); abikestore is the argument from the right side of the = operator

36 Definition of = The definition of = for BikeStore could be: void BikeStore::operator = (const BikeStore& abikestore) { cout << "Calling Assignment Operator\n"; if(mcapacity < abikestore.mcapacity) { delete [] minventory; minventory = new Bike[aBikeStore.mCapacity]; mcapacity = abikestore.mcapacity; } for(int i = 0; i < abikestore.msize; i++) { minventory[i] = abikestore.minventory[i]; } msize = abikestore.msize; } // not a complete version of the assignment operator

37 Side affects In the previous slide the assignment operator is defined as a void function. Defining the assignment operator as a void function stops us from writing code like: BikeStore a; BikeStore b; BikeStore c; c = b = a; // this would not work because we ve defined the operator as // void function we must return a BikeStore for this to work

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More 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

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Review: C++ Basic Concepts. Dr. Yingwu Zhu Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to

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

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

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

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

C++ 8. Constructors and Destructors

C++ 8. Constructors and Destructors 8. Constructors and Destructors C++ 1. When an instance of a class comes into scope, the function that executed is. a) Destructors b) Constructors c) Inline d) Friend 2. When a class object goes out of

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

EECE.3220: Data Structures Spring 2017

EECE.3220: Data Structures Spring 2017 EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University (5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University Key Concepts Function templates Defining classes with member functions The Rule

More information

Ch02. True/False Indicate whether the statement is true or false.

Ch02. True/False Indicate whether the statement is true or false. Ch02 True/False Indicate whether the statement is true or false. 1. The base class inherits all its properties from the derived class. 2. Inheritance is an is-a relationship. 3. In single inheritance,

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 9 Classes : A Deeper Look, Part 1

Chapter 9 Classes : A Deeper Look, Part 1 Chapter 9 Classes : A Deeper Look, Part 1 C++, How to Program Deitel & Deitel Fall 2016 CISC1600 Yanjun Li 1 Time Class Case Study Time Class Definition: private data members: int hour; int minute; int

More information

Implementing an ADT with a Class

Implementing an ADT with a Class Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the

More information

Intermediate Programming & Design (C++) Classes in C++

Intermediate Programming & Design (C++) Classes in C++ Classes in C++ A class is a data type similar to a C structure. It includes various local data (called data members) together with constructors, destructors and member functions. All of them are called

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 4 Date:

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

Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373

Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Overview Object Creation Control Distribution Possibilities Impact of design decisions on IP control 2 Good

More information

Comp151. Generic Programming: Container Classes

Comp151. Generic Programming: Container Classes Comp151 Generic Programming: Container Classes Container Classes Container classes are a typical use for class templates, since we need container classes for objects of many different types, and the types

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

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

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/11/lab11.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 1 The purpose of this assignment is to become more familiar with

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

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory Outline 1 Chapter 10: C++ Dynamic Memory Proper Memory Management Classes which must allocate memory must manage it properly. Default behavior of operations in C++ are insufficient for this. The assignment

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

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming Chapter 13: Introduction to Classes 1 13.1 Procedural and Object-Oriented Programming 2 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a

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

Abstraction in Software Development

Abstraction in Software Development Abstract Data Types Programmer-created data types that specify values that can be stored (type of data) operations that can be done on the values The user of an abstract data type (ADT) does not need to

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

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

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; } Multiple choice questions, 2 point each: 1. What output is produced by the following program? #include int f (int a, int &b) a = b + 1; b = 2 * b; return a + b; int main( ) int x=1, y=2, z=3;

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

Recharge (int, int, int); //constructor declared void disply();

Recharge (int, int, int); //constructor declared void disply(); Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize

More information

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related

More information

Introduction to Classes

Introduction to Classes Introduction to Classes Procedural and Object-Oriented Programming Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented

More information

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F

Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F Dynamic memory in class Ch 9, 11.4, 13.1 & Appendix F Announcements Test next week (whole class) Covers: -Arrays -Functions -Recursion -Strings -File I/O Highlights - Destructors - Copy constructors -

More information

INHERITANCE: CONSTRUCTORS,

INHERITANCE: CONSTRUCTORS, INHERITANCE: CONSTRUCTORS, DESTRUCTORS, HEADER FILES Pages 720 to 731 Anna Rakitianskaia, University of Pretoria CONSTRUCTORS Constructors are used to create objects Object creation = initialising member

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

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

ComS 228 Exam 1. September 27, 2004

ComS 228 Exam 1. September 27, 2004 ComS 228 Exam 1 September 27, 2004 Name: University ID: Section: (10 percent penalty if incorrect) This is a one-hour, closed-book, closed-notes, closed-calculator exam. The exam consists of 9 pages (including

More information

การทดลองท 8_2 Editor Buffer Array Implementation

การทดลองท 8_2 Editor Buffer Array Implementation การทดลองท 8_2 Editor Buffer Array Implementation * File: buffer.h * -------------- * This file defines the interface for the EditorBuffer class. #ifndef _buffer_h #define _buffer_h * Class: EditorBuffer

More information

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science Written examination Homologation C++ and Computer Organization (2DMW00) Part I: C++ - on Tuesday, November 1st 2016, 9:00h-12:00h.

More information

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 14 for ENCM 339 Fall 2015 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary Fall Term, 2015 SN s ENCM 339 Fall 2015 Slide Set 14 slide

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 9, 2016 Outline Outline 1 Chapter 9: C++ Classes Outline Chapter 9: C++ Classes 1 Chapter 9: C++ Classes Class Syntax

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Object-Oriented Programming in C++

Object-Oriented Programming in C++ Object-Oriented Programming in C++ Pre-Lecture 9: Advanced topics Prof Niels Walet (Niels.Walet@manchester.ac.uk) Room 7.07, Schuster Building March 24, 2015 Prelecture 9 Outline This prelecture largely

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

More information

Praktikum: Entwicklung interaktiver eingebetteter Systeme

Praktikum: Entwicklung interaktiver eingebetteter Systeme Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Labs (falk@cs.fau.de) 1 Agenda Writing a Vector Class Constructor, References, Overloading Templates, Virtual Functions Standard Template Library

More information

Exam 3 Chapters 7 & 9

Exam 3 Chapters 7 & 9 Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False

More information

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

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

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13 This chapter focuses on introducing the notion of classes in the C++ programming language. We describe how to create class and use an object of a

More information

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

QUIZ How do we implement run-time constants and. compile-time constants inside classes? QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of

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

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

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

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

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

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

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data

More information

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; } . CONSTRUCTOR If the name of the member function of a class and the name of class are same, then the member function is called constructor. Constructors are used to initialize the object of that class

More information

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University C++ Review CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose of Review Review some basic C++ Familiarize us with

More information

Class and Function Templates

Class and Function Templates Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

Do not write in this area TOTAL. Maximum possible points: 75

Do not write in this area TOTAL. Maximum possible points: 75 Name: Student ID: Instructor: Borja Sotomayor Do not write in this area 1 2 3 4 5 6 7 TOTAL Maximum possible points: 75 This homework assignment is divided into two parts: one related to the fundamental

More information

Week 8: Operator overloading

Week 8: Operator overloading Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 14 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2016 ENCM 339 Fall 2016 Slide Set 14 slide 2/35

More information

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Motivation for Templates. Class and Function Templates. One Way to Look at Templates... Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates...

More information

GEA 2017, Week 4. February 21, 2017

GEA 2017, Week 4. February 21, 2017 GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,

More information

Macros and Preprocessor. CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang

Macros and Preprocessor. CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang Macros and Preprocessor CGS 3460, Lecture 39 Apr 17, 2006 Hen-I Yang Previously Operations on Linked list (Create and Insert) Agenda Linked List (More insert, lookup and delete) Preprocessor Linked List

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

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

More information

Scope. Scope is such an important thing that we ll review what we know about scope now:

Scope. Scope is such an important thing that we ll review what we know about scope now: Scope Scope is such an important thing that we ll review what we know about scope now: Local (block) scope: A name declared within a block is accessible only within that block and blocks enclosed by it,

More information

CSE 333 Midterm Exam July 24, Name UW ID#

CSE 333 Midterm Exam July 24, Name UW ID# Name UW ID# There are 6 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

pointers & references

pointers & references pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428

More information

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 2 Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Arrays and Pointers void myprint(const char *); int main() { char *phrasey = C++Fun ; myprint(phrasey);

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

Use the dot operator to access a member of a specific object.

Use the dot operator to access a member of a specific object. Lab 16 Class A class is a data type that can contain several parts, which are called members. There are two types of members, data member and functions. An object is an instance of a class, and each object

More information

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members Chapter 14: More About Classes 14.1 Instance and Static Members Instance and Static Members instance variable: a member variable in a class. Each object has its own copy. static variable: one variable

More information

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4) Classes and Objects in C++: Operator Overloading CSC 112 Fall 2009 Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2305/lab06.(C CPP cpp c++ cc cxx cp) Input: Under control of main function Output: Under control of main function Value: 2 Extend the IntegerSet class from Lab 04 to provide the following

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More 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

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - The Preprocessor Outline 17.1 Introduction 17.2 The #include Preprocessor Directive 17.3 The #define Preprocessor Directive: Symbolic Constants 17.4 The

More information

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3

PIC 10B Lecture 1 Winter 2014 Homework Assignment #3 PIC 10B Lecture 1 Winter 2014 Homework Assignment #3 Due Tuesday, February 4, 2014 by 5:00pm. Objectives: 1. To redefine the Big 3 : Copy constructor, Assignment operator, and Destructor for a class whose

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

More information