CE221 Programming in C++ Part 1 Introduction

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

Object Oriented Design

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CSE 303: Concepts and Tools for Software Development

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

Interview Questions of C++

Chapter 2. Procedural Programming

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

Operator overloading

Introduction to Programming using C++

CS2141 Software Development using C/C++ C++ Basics

Fast Introduction to Object Oriented Programming and C++

6.096 Introduction to C++ January (IAP) 2009

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

Chapter 15 - C++ As A "Better C"

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Programmazione. Prof. Marco Bertini

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

C++ Programming Fundamentals

CS 376b Computer Vision

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

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

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Motivation was to facilitate development of systems software, especially OS development.

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

A A B U n i v e r s i t y

COMP322 - Introduction to C++ Lecture 01 - Introduction

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Structure of this course. C and C++ Past Exam Questions. Text books

Lecture 2, September 4

Your first C++ program

BLM2031 Structured Programming. Zeyneb KURT

The New C Standard (Excerpted material)

Computer Science II Lecture 1 Introduction and Background

AN OVERVIEW OF C++ 1

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Introduction to C++ Systems Programming

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

PIC 10A Objects/Classes

Lesson 13 - Vectors Dynamic Data Storage

Outline. 1 About the course

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Lab # 02. Basic Elements of C++ _ Part1

Getting started with C++ (Part 2)

2. COURSE DESIGNATION: 3. COURSE DESCRIPTIONS:

Partha Sarathi Mandal

COEN244: Class & function templates

III. Classes (Chap. 3)

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Scientific Computing

Computer Programming : C++

C++ Lab 03 - C++ Functions

Motivation was to facilitate development of systems software, especially OS development.

G52CPP C++ Programming Lecture 9

Programming in C and C++

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

377 Student Guide to C++

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

Syllabus of C++ Software for Hands-on Learning: This course offers the following modules: Module 1: Getting Started with C++ Programming

CPSC 427: Object-Oriented Programming

Absolute C++ Walter Savitch

Your first C and C++ programs

Advanced Systems Programming

#include <iostream> #include <cstdlib>

My First Command-Line Program

Intermediate Programming, Spring 2017*

CS201 Latest Solved MCQs

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CS3215. Outline: 1. Introduction 2. C++ language features 3. C++ program organization

CE204 Data Structures and Algorithms Part 1

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Object-Oriented Design (OOD) and C++

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Chapter 2: Introduction to C++

A brief introduction to C++

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Cours de C++ Introduction

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

COMP322 - Introduction to C++

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Fundamentals of Programming Session 12

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

C++ Quick Guide. Advertisements

Lab 1: First Steps in C++ - Eclipse

A Fast Review of C Essentials Part I

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Programming, numerics and optimization

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Variables. Data Types.

Dr. Md. Humayun Kabir CSE Department, BUET

Polymorphism Part 1 1

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

CSc Introduction to Computing

Transcription:

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 at either 9.00 on Wednesdays or 4.00 on Thursdays. (Note that the labs start in week 3 there are none in week 2). There will also be two revision lectures in the summer term. 06/10/2017 CE221 Part 1 2

Assessment One two-hour examination in May/June (60% of the module credit) Two programming assignments to be submitted by noon on Monday of week 8 and Wednesday of week 16 (20% each) You will be required to demonstrate your submitted programs for the first assignment in the lab in week 8 or 9. (Note that this module has no week 6 test.) 06/10/2017 CE221 Part 1 3

Recommended Reading The main recommended text for this module is Thinking in C++, B. Eckel, Volume 1, 2 nd edition (Prentice Hall, 2000) available for free download at http://www.agitate.org.uk/eckel Alternative books include C++: How to Program, H.M. Deitel and P.J. Deitel, 5 th edition (Prentice Hall, 2005) C++ for Java Programmers, T. Budd (Addison Wesley, 1999), and the definitive reference The C++ Programming Language, B. Stroustrup, 3 rd edition (Addison Wesley, 2000). 06/10/2017 CE221 Part 1 4

Motivation for Learning C++ C++ is more powerful and efficient than other high-level programming languages (although more complicated). C and C++ are the most widely used programming languages for robotics and games, and for writing compilers and operating systems and drivers of hardware devices. Consequently a knowledge of C++ is a big advantage in the jobs market. 06/10/2017 CE221 Part 1 5

Learning Outcomes After completing this module, students will be expected to be able to explain the basic concepts and features of C++. describe the underlying memory model and explain the role of the execution stack and the heap. write object-oriented programs that incorporate basic C++ features such as pointers, references, inheritance, function overriding, operator overloading, exceptions, etc. make effective use of the C++ Standard Template Library. 06/10/2017 CE221 Part 1 6

Lecture Outline The lectures for this module are divided into three main parts: Basics: fundamental types and variables, memory management, references, pointers, arrays, control structures, functions, classes and objects, operator overloading, an Array class, the string class, file processing, comparison of C++ and Java. Libraries: templates (function templates and class templates), containers, iterators, algorithms, the Standard Template Library (STL). Advanced topics: inheritance, polymorphism, exception handling. 06/10/2017 CE221 Part 1 7

C++ Development Environments Development of a C++ program involves six phases: edit, pre-process, compile, link, load, execute. Disk Memory CPU Popular IDEs include Borland C++, Visual C++, MFC. However, in the labs we shall be using TextPad. 06/10/2017 CE221 Part 1 8

Hello World in Java, C and C++ 1 // Java public class HelloWorld { public static void main(string args[]) { System.out.print("\nHello, World!\n"); } } /* C */ #include <stdio.h> /* could use int main() */ main() /* default return type is int */ { printf("\nhello, World!\n"); } 06/10/2017 CE221 Part 1 9

Hello World in Java, C and C++ 2 // C++ #include <iostream> // using namespace std; // could use int main(int argc, char* argv[]) or // int main(int argc, char* argv[], char **env) main() // default return type is int { // cout << "\nhello, World!\n"; std::cout << "\nhello, World!\n"; // return 0; } 06/10/2017 CE221 Part 1 10

Some Notes on the C++ Version 1 The main method in a C++ program is not written inside a class; the term function is used instead of method. The main function may take arguments to access commandline arguments, but these are optional; its return type is int. However, when a function is declared without a return type it is by default given the type int so we can simply write main() It is not regarded as an error if a function fails to return a result; in this case the result is unspecified. Since no attempt will be made to access the result returned by main we may hence omit the return statement. 06/10/2017 CE221 Part 1 11

Some Notes on the C++ Version 2 Screen output is sent to a stream called cout, defined in a namespace called std. We have to inform the compiler of the namespace: we can do this explicitly using std::cout, or we can use a using statement (as seen in the commented-out line) to indicate that we wish to use the namespace std to resolve any otherwise undeclared identifiers and then simply use cout. The << operator is used to send values to be output to a stream; we may chain these, e.g. cout << '\n' << "Hello, World!" << '\n'; 06/10/2017 CE221 Part 1 12

Some Notes on the C++ Version 3 In Java information about external classes is stored in their.class files and we import these; however in C++ (and C) this information is stored in the form of declarations in a text file called a header and to make these available to the compiler we must include the contents of appropriate header files within the source code using #include. The header file(s) will be copied onto a temporary copy of the source file before the main compilation process begins; the compiler then uses this temporary file as the source file. (The temporary file is annotated with information about the line numbers from the original files so that error messages can correctly report line numbers.) 06/10/2017 CE221 Part 1 13

Hello World Using a Class 1 We now present a version of a Hello World program in which the output is produced in a class and the main function makes a call to a function in this class. #include <iostream> using namespace std; // HelloWorld class definition // (a user-defined type) class HelloWorld { public: void displaymessage() { cout << endl << "Hello, World!" << endl; } }; // semicolon to terminate class definition 06/10/2017 CE221 Part 1 14

Hello World Using a Class 2 Here is the rest of the program. int main() { HelloWorld myhelloworld; myhelloworld.displaymessage(); return 0; } It is conventional to start class names with upper-case letters and variables and function names with lower-case letters. We have used endl instead of '\n'; this makes the program easier to read. The term member function is used in C++ to refer to a method of a class. 06/10/2017 CE221 Part 1 15

Hello World Using a Class 3 Note that as in Java, a default no-argument constructor is generated if we do not provide any constructor for a class. Furthermore, unlike in Java, if we declare an object variable without initialisation its no-argument constructor is called implicitly. Hence we simply use HelloWorld myhelloworld; Note that the new keyword in C++ does something slightly different to that in Java so an attempt to use HelloWorld myhelloworld = new HelloWorld(); would result in a compilation error. 06/10/2017 CE221 Part 1 16

Using Separate Files 1 Most classes written in C++ will be expected to be reused so it is common practice to write each class in a separate file, along with a header file that can be included in each file that uses the class. Although this is, of course, unnecessary for our simple program, we shall perform the splitting into separate files in order to demonstrate how to do this. A class definition containing all of its variables and the declarations of all of its functions without their bodies is placed in a header file with a.h extension; the complete function definitions are then provided in a source file for the class with a.cpp extension. 06/10/2017 CE221 Part 1 17

Using Separate Files 2 The header file for our HelloWorld class will be // HelloWorld.h class HelloWorld { public: void displaymessage(); }; The file containing the main function will be // HelloMain.cpp #include "HelloWorld.h" int main() { HelloWorld myhelloworld; myhelloworld.displaymessage(); return 0; } 06/10/2017 CE221 Part 1 18

Using Separate Files 3 Note that when including files that are in the user's folders we specify the filename(s), including the.h extension, inside quotes in the #include directive(s). The angled brackets as used for #include <iostream> are used for header files that are found in the C++ system folders. It would be possible simply to write the complete definition of the HelloWorld class in a HelloWorld.cpp file; however the compiler will then not perform any checks to see if the definition is consistent with that in the header file. When developing classes that will be modified as we proceed it is essential that such checks are performed. Hence the header file should be included in the class file. 06/10/2017 CE221 Part 1 19

Using Separate Files 4 Assuming the HelloWorld.h file is to be included in the HelloWorld.cpp file its contents will be copied into the the latter file at compilation time. Hence this file will contain a definition for the HelloWorld class and we cannot write another definition in the file. Consequently we have to write the function body outside of the class definition and indicate that it is a member of the class by prefixing its name with the class name using void HelloWorld::displayMessage() The source file for the class can be seen on the next slide. 06/10/2017 CE221 Part 1 20

Using Separate Files 5 #include <iostream> #include "HelloWorld.h" using namespace std; void HelloWorld::displayMessage() { cout << endl << "Hello, World!" << endl; } 06/10/2017 CE221 Part 1 21

Avoiding Duplicate Header Inclusion 1 Many header files need to include other header files; for example any header file with classes which have members of type string would need to contain the line #include <string> If a user's program included more than one such file the nested includes would result in the header file for the string class being included more than once in his program. We might expect that this would lead to compilation errors due to duplicate class definitions. This however is not the case; the header file for the string class has been written in such a way that if the class declaration has already been included it will not be included again. 06/10/2017 CE221 Part 1 22

Avoiding Duplicate Header Inclusion 2 The contents of header files are inserted into the temporary of the source file by the preprocessor, the first step of the compilation process. To prevent class declarations being duplicated header files should use preprocessor directives to provide conditional inclusion: // myclass.h #ifndef _MYCLASS_H_ #define _MYCLASS_H_ // use names like _MYCLASS_H_ to avoid // potential clashes with program variable // names // body of header file comes here #endif 06/10/2017 CE221 Part 1 23

Avoiding Duplicate Header Inclusion 3 In the example on the previous slide when a first attempt is made to include the file the preprocessor will find that the preprocessor variable _MYCLASS_H_ has not been defined so the contents of the file will be included. The next line of the file is a preprocessor directive to define this variable (giving it an empty string as a value, since there is nothing on the line after the name of the variable). The body of the header file is then included in the source program. If a second attempt is then made to include the file the preprocessor will find that the variable has been defined so all lines between the #ifndef directive and its matching #endif will be ignored. 06/10/2017 CE221 Part 1 24

Avoiding Duplicate Header Inclusion 4 Here is a version of HelloWorld.h that uses preprocessor directives to avoid any possibility of duplicate inclusion. // HelloWorld.h #ifndef _HELLOWORLD_H_ #define _HELLOWORLD_H_ class HelloWorld { public: void displaymessage(); }; #endif 06/10/2017 CE221 Part 1 25

A Typical C++ Program Framework // Class1.h #ifndef _CLASS1_H_ #define _CLASS1_H_ // include headers class Class1 { public: Class1(/* args* /); // other members private: // members }; #endif (Add more classes: Class2, Class3, ) // Class1.cpp // include headers Class1::Class1(/* args */) { // constructor // implementation } // implementation of other // members // main.cpp // include headers main(int argc, char *argv[]) { // create objects, use them } 06/10/2017 CE221 Part 1 26

Primitive Types 1 C++ has a large number of primitive types: bool char short int (or short) int long int (or long) long long int (or long long) unsigned char unsigned short int (or unsigned short) unsigned int (or unsigned) unsigned long int (or unsigned long) unsigned long long int (or unsigned long long) float double long double 06/10/2017 CE221 Part 1 27

Primitive Types 2 The value of a data item of type bool is either true or false. Any numeric value may be used in a context where a boolean is required; non-zero values are interpreted as true and 0 as false. The next 10 types listed on the previous slide are all regarded as integer types and it is possible to freely assign between them overflow may of course occur. The unsigned versions cannot hold negative values: an initialisation such as unsigned int i = -1; will result in the value of i being the integer that has the same value as the two's complement representation of -1, i.e. the maximum value for the type int. 06/10/2017 CE221 Part 1 28

Primitive Types 3 The range of values that may be stored in a data item of each type is hardware-dependent. A char will almost invariably have 8 bits, a short will have at least 16 bits and a long will have at least 32 bits. The unsigned versions will always have the same number of bits as their signed counterparts. In most modern implementations the short type uses 16 bits, both int and long use 32 bits and long long uses 64 bits. The float type usually uses 32 bits, double 64 bits and long double 128 bits. Since in some older implementations the int type has only 16 bits it is wise to use long for any variable or class member that is expected to sometimes take values larger than 32767. 06/10/2017 CE221 Part 1 29

Memory and Storage The computer memory for a C++ program has four areas. There is an area which stores the code and constants. This is pretty much invariant the code shouldn t change. Data items are stored in three areas: a static area for items whose lifetime is the duration of the program. a stack area for local variables in functions, whose lifetime is the invocation of a function; this area is also used to pass arguments to functions and return results, and to store return addresses. a heap area for dynamic items, whose lifetime is controlled by the programmer 06/10/2017 CE221 Part 1 30

Variables A variable in a programming language has three major attributes. It has a type (e.g. int, bool, string, Student). Types may be primitive or classes. It has lifetime (or extent). It is born, it is used, it dies. It has scope (or visibility). When it is in existence, what other things can see it? It also has a name, a size (i.e. how much memory it occupies), and a value. 06/10/2017 CE221 Part 1 31

Storage Classes and Variable Lifetime 1 There are five storage classes: automatic: for local variables only, existing only when the block in which the variables are defined is active. register: for local variables only, for fast access, rarely used nowadays. mutable: for class members only, to make them always modifiable even in a const member function or as a member of a const object. external: for identifier linkage of global variables and functions, lasting for the duration of the program. static: for variables and class members that last for the duration of the program and can be initialised once only There are five keywords that can be used to indicate that a variable should have one of these classes: auto, register, mutable, extern and static. 06/10/2017 CE221 Part 1 32

Storage Classes and Variable Lifetime 2 Since local variables are usually stored on the stack by default it is rare that the auto keyword needs to be used and since C++11 it is no longer used for this purpose but has a totally different meaning. The register class is used to indicate that a frequently-accessed local variable should be stored in a register instead of memory in order to optimise performance; such optimisations are rarely necessary on modern machines. A const member function cannot normally change the values of members of the object to which it is applied. There may be rare occasions when we wish to allow the value of a particular member to be changed in such a function (for example, during program development it may be desirable to add an access counter when analysing for possible optimisations), hence the need for mutable variables. 06/10/2017 CE221 Part 1 33

Storage Classes and Variable Lifetime 3 A static data item exists for the duration of the program and can be initialised only once. Classes can have static members; in this case one copy is shared by all of the objects of that class. If a local variable in a function is declared to be static it is initialised when the program starts running and retains its value between calls to that function. A static variable must be initialised with a value when it is declared, e.g. static int x = 77; // not static int x; 06/10/2017 CE221 Part 1 34

Storage Classes and Variable Lifetime 4 A global variable is one that is defined outside any class or function. If a program is split between several files it may be necessary to access the same global variable in more than one file. The variable can however be declared in only one of the files so in all of the others it must be declared as external. For example, if one file contains the global declaration int a = 5; and we need to access a in another file we would need to include the declaration extern int a; in that file. This if often done by placing the line in a header file associated with the first file and included in the second file. 06/10/2017 CE221 Part 1 35

Scope 1 The scope of a variable specifies where in the program it can be accessed. A variable declared locally in a block of code can be accessed only between its declaration and the end of that block. If, within the block we make a call to a function, the variable cannot be accessed within the function. A private member of a class can be accessed only within that class and its member functions and friend functions (we shall see what a friend function is later). The member functions may be defined outside the class body as seen in our example on slide 20. If our HelloWorld class had any private members they would have been accessible in the displaymessage function. 06/10/2017 CE221 Part 1 36

Scope 2 A local variable may have the same name as a variable that is already in scope; the following code fragment is valid. int a = 0; // global int myfunc() { char a = 'x'; }; Within the body of myfunc any occurrence of a will refer to the local variable. If we need to access the global variable we must use ::a. 06/10/2017 CE221 Part 1 37

#include <iostream> using namespace std; int a = 1; void f() { int b = 1; Example and Exercise static int c = a; // initialised once only int d = a; // initialised at each call of f() cout << "a=" << a++ << " b=" << b++ << " c=" << c << " d=" << d << endl; c+=2; } int main() { while (a<4) f(); } What are the scope and lifetime of a, b, c and d? What would be the outputs? 06/10/2017 CE221 Part 1 38