G52CPP C++ Programming Lecture 9

Similar documents
G52CPP C++ Programming Lecture 7. Dr Jason Atkin

G52CPP C++ Programming Lecture 8. Dr Jason Atkin

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

G52CPP C++ Programming Lecture 10. Dr Jason Atkin

G52CPP C++ Programming Lecture 12

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

QUIZ Friends class Y;

Fast Introduction to Object Oriented Programming and C++

CSE 303: Concepts and Tools for Software Development

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

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

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula

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

Variables and literals

G52CPP C++ Programming Lecture 20

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

CE221 Programming in C++ Part 1 Introduction

Classes. C++ Object Oriented Programming Pei-yih Ting NTOU CS

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 15

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

1c) (iv) and (v) OR (v) only (hindsight showed that the question was more ambiguous than intended)

QUIZ. What is wrong with this code that uses default arguments?

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

An Introduction to C++

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

Ticket Machine Project(s)

CSE 374 Programming Concepts & Tools

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

C++ (Non for C Programmer) (BT307) 40 Hours

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Principles of Object Oriented Programming. Lecture 4

Software Design and Analysis for Engineers

Object-Oriented Programming

Kurt Schmidt. October 30, 2018

Separate Compilation Model

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

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

10. Object-oriented Programming. 7. Juli 2011

G52PGP. Lecture OO2 Object Oriented programming in C

Interview Questions of C++

Pointers and scanf() Steven R. Bagley

Ch. 10: Name Control

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

C++ Inheritance and Encapsulation

Object Oriented Programming in C#

Advanced Systems Programming

#include <iostream> #include <cstdlib>

Heap Arrays. Steven R. Bagley

Short Notes of CS201

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

CS304 Object Oriented Programming Final Term

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Implementing Subprograms

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

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

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

CS201 - Introduction to Programming Glossary By

G52CPP C++ Programming Lecture 16

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

STRUCTURING OF PROGRAM

Sums. Here's a (poor) program to add three numbers

RECOMMENDATION. Don't Write Entire Programs Unless You Want To Spend 3-10 Times As Long Doing Labs! Write 1 Function - Test That Function!

COMP 2355 Introduction to Systems Programming

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

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

2.1 Introduction UML Preliminaries Class diagrams Modelling delegation... 4

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Chapter 4 Defining Classes I

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

CPSC 427: Object-Oriented Programming

Heap Arrays and Linked Lists. Steven R. Bagley

ECE 15B COMPUTER ORGANIZATION

Introduction to Classes

Computer Science 306 Study Guide

Programming Exercise 14: Inheritance and Polymorphism

COMP322 - Introduction to C++

QUIZ. How could we disable the automatic creation of copyconstructors

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

Chapter 15: Object Oriented Programming

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

Supporting Class / C++ Lecture Notes

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Object Oriented Design

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Common Misunderstandings from Exam 1 Material

Programming in C and C++

Software Engineering /48

Object Oriented Programming. Solved MCQs - Part 2

Review of the C Programming Language for Principles of Operating Systems

Laboratorio di Tecnologie dell'informazione

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

QUIZ. How could we disable the automatic creation of copyconstructors

CLASSES AND OBJECTS IN JAVA

What are the characteristics of Object Oriented programming language?

Lecture 2, September 4

Transcription:

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 multiple header files Linkage and visibility Demos of these things later today 2

Avoiding multiple inclusion Code to include the contents of a file only once: #ifndef UNIQUE_DEFINE_NAME_FOR_FILE #define UNIQUE_DEFINE_NAME_FOR_FILE include the rest of the file here #endif To work, the name in the #define has to be unique throughout the program E.g. you probably should include the path of the header file, not just the filename Example: mycode/game/graphics/screen.h could be called MYCODE_GAME_GRAPHICS_SCREEN_H By convention, #defines are in upper case 3

Example coursework file #ifndef DISPLAYABLEOBJECT_H #define DISPLAYABLEOBJECT_H #include "BaseEngine.h" If not already marked as included Mark it as included now, by setting the #define Includes the header files it needs class DisplayableObject { public: // Constructor DisplayableObject(BaseEngine* pengine); // Destructor virtual ~DisplayableObject(void); private: // True if item is visible bool m_bvisible; }; #endif End of the #ifdef around the contents 4

Three rules for header files 1. Ensure that the header file #includes everything that it needs itself i.e. #include any headers it depends upon 2. Ensure that it doesn t matter if the header file is included multiple times See previous slides 3. Ensure that header files can be included in any order A consequence of the first two rules 5

#define and macro definitions You can use #define to define a macro: #define max(a,b) (((a)>(b))? (a) : (b)) int v1 = max( 40, 234 ); int v1 = (((40)>(234))? (40) : (234)) int v2 = max( v1, 99 ); int v2 = (((v1)>(99))? (v1) : (99)) int v3 = max ( v1, v2 ); int v3 = (((v1)>(v2))? (v1) : (v2)) Remember: done by the pre-processor! NOT a function call 6

MyHeader.h What is the output here? #ifndef MY_HEADER_H #define MY_HEADER_H #define max(a,b) (((a)>(b))? (a) : (b)) #endif MyTest.cpp #include <cstdio> #include MyHeader.h int main( int argc, char* argv[] ) { int a = 1, b = 1; while ( a < 10 ) { printf( a = %d, b = %d, a, b ); printf( max = %d\n, max(a++,b++) ); } } 7

The (surprise?) output printf( a = %d, b = %d, a, b ); printf( max = %d\n, max(a++,b++) ); The output is: a = 1, b = 1 max = 2 a = 2, b = 3 max = 4 a = 3, b = 5 max = 6 a = 4, b = 7 max = 8 a = 5, b = 9 max = 10 a = 6, b = 11 max = 12 a = 7, b = 13 max = 14 a = 8, b = 15 max = 16 a = 9, b = 17 max = 18 Why? max( a++, b++ ) expands to: ((a++)>(b++))? (a++) : (b++) So, whichever number is greater will get incremented twice, and the lesser number only once 8

Warning about macros Do not use a macro where the evaluation of the parameters may have a side-effect E.g. max(a++,b++) Evaluating these parameters alters a value A side-effect 9

This lecture classes (and C++ structs) Member functions inline functions 10

classes and structs A very quick introduction Something to refer back to Differences between C++ and Java 11

C++ vs C structs Can still use structs in C++ Everything for structs so far applies to both C and C++ We will call them C-style structs If you use only C features, structs in C++ work as for C, i.e. you can predict sizeof(), can malloc() space for them, etc Everything we have seen so far is valid In C++ you can add functions to structs If you use ANY C++ only features (e.g. add functions or use inheritance), their behaviour may change If you have used ANY C++ only features, DO NOT try to treat them as C structs you may get a nasty surprise e.g. size may grow or it may have hidden parts (see later lectures) 12

classes and structs classes and structs are (almost) the same thing in C++ The difference is (ONLY!!!) in encapsulation struct defaults to public, class to private Everything you do with a class in C++ could also be done with a struct Common coding practice in C++: Data only and no member functions: use a struct You get the guarantees about size and positions of member data that you get in a C struct If you add member functions, use a class Advice: use struct only for C-type structs 13

Methods / member functions In C++, functions can be made class/struct members Just like Java functions #include <cstdio> struct Print { void print() { printf( "Test\n" ); } }; int main() { Print p; p.print(); } Create a struct on stack as in C Call a method on the struct If we had a struct* we would use p->print(); 14

Hiding data inside classes (or structs) Data and methods in a class have either public or private access There is also protected we will see later public methods and data can be accessed by anything Like non-static global functions/data in a file private methods and data can only be accessed by other members of the SAME class Like static global functions/data in a file Note: There is no package only access class members default to private access struct members default to public access 15

Methods/functions and data Data should (usually) be private If it is not, then have a VERY good justification Methods (functions) should be: private for internal use only public for the external class interface The values of the data members comprise the state of the object Interface methods can be: Mutators change the state of the object Accessors only query values, no changes Note: inline functions (see later) for methods ensure that it is no slower at runtime to use accessors than to use the variable names 16

public and private Keyword private: will change access to private from then onwards Keyword public: will change access to public class DemoClass { public: int GetValue() { return m_ivalue; } void SetValue( int ivalue ) { m_ivalue = ivalue; } private: int m_ivalue; }; public: for the interface Public from this point onward private: for data and internal functions Private from this point onwards 17

Member functions and data Member data should be private Accessor and mutator functions could be public including getters and setters class DemoClass { public: int GetValue() { return m_ivalue; } void SetValue( int ivalue ) { m_ivalue = ivalue; } private: Member data/attributes/state int m_ivalue; }; Methods/member functions/operations Semi-colon at the end 18

Some advance knowledge You can use inheritance, e.g.: class SubClass : public BaseClass { <Data and methods> } Like extends in Java Member functions can access the data in classes or structs There is a hidden this pointer Like the hidden this object reference in Java Use this-> not this. static member data and functions work as per Java, shared between instances, no this pointer 19

Constructors and destructors 20

Constructors and Destructors Constructor Called when an object is created Has function name same as class name And no return type (none/empty, NOT void!) Adding a constructor makes it impossible to provide a C-style initialiser. e.g. = {0,1,2}; Look back at the slides on initialisers for structs in C No constructor => you can use the C-style initialiser Destructor (similar to Java finalize) Called when an object is destroyed A function with name ~ then class name E.g.: ~DemoClass() And no return type 21

Example C++ class class DemoClass { public: DemoClass() { } ~DemoClass() { } Constructor No return type Destructor No return type Accessor Access only, no changes Ideally label the function with keyword const (see later lecture for why) int GetValue() const { return m_ivalue; } void SetValue( int ivalue ) { m_ivalue = ivalue; } private: int m_ivalue; }; Mutator. Mutates/changes the object Data member/member variable/attribute 22

Constructor parameters You can pass parameters to constructors You can have multiple constructors Which differ in which parameter types they expect The compiler will consider which parameters are passed in order to determine which constructor to use In the same way as functional overloading You are probably used to this from Java General C++ rule: if your code introduces ambiguity (i.e. this could mean A or B) then it will not compile If the constructor that the compiler should call is ambiguous, the code will not compile! 23

Passing parameters to constructors 1. Create a constructor which takes parameters e.g. a constructor which takes an int: DemoClass(int ivalue) { } // In class DemoClass 2. To create an object on the stack, passing values to constructor use: DemoClass mydemoclass(4); 24

Default parameters In C++, parameters can have default values So can parameters in constructors Use the = <value> syntax following the parameter declaration e.g.: DemoClass( char* dummy, int ivalue = -1) { /*Nothing*/ } Will match any of the following: DemoClass mydemoclass3( "Temp", 3 ); DemoClass mydemoclass4( "Temp" ); Default values appear only in the function declaration, not any separate definition 25

Default Constructor The Default Constructor is a constructor which can be called with no parameters e.g. one which has no parameters or has default values for all parameters A class can only have one default constructor More would introduce ambiguity When you create arrays of objects, the default constructor is used (because no parameters are provided): e.g.: DemoClass mydemoarray[4]; 26

Constructor parameters or not? Create an object, using default constructor DemoClass mydemoclass1; Or create an object, passing values to the constructor (selects the constructor to use) DemoClass mydemoclass3( "Temp" ); IMPORTANT: Do NOT add empty brackets () when constructing on the stack if there are no parameters! Compiler thinks you are declaring a function e.g. DemoClass mydemoclass1(); // WRONG!!! 27

Basic types Basic types can be initialised in the same way as classes (using the brackets) Create an int (we have seen this a lot) int ival = 4; // Initialisation! The () form can also be used for basic types int ival(4); // Initialisation! Both do exactly the same thing 28

Initialisation list Initialisation list allows you to pass values to: Data member constructors Base class constructors Uses the () form of initialisation i.e. initialisation values to use are inside () Uses the : operator following the constructor parameters (before the opening brace): DemoClass(int ivalue) : m_ivalue(ivalue) {} Initialisation list, comma separated 29

Example Initialisation List class DemoClass { public: DemoClass( int ivalue ) : m_ivalue(ivalue) { } ~DemoClass() { } int GetValue() { return m_ivalue; } void SetValue(int ivalue) { m_ivalue = ivalue; } private: int m_ivalue; }; 30

Two ways to set member values With an int type data member called m_ivalue Compare the following: DemoClass(int ivalue) : m_ivalue(ivalue) {} With the following: DemoClass(int ivalue) { } m_ivalue = ivalue; Question: Are these the same? 31

Initialisation vs Assignment (1) class DemoClass { public: DemoClass( int ivalue ) : m_ivalue(ivalue) { } Note: You could only have ONE of the following in a class, since they have the same parameters m_ivalue is initialised with value ivalue DemoClass(int ivalue) { } m_ivalue = ivalue; m_ivalue is created but not initialised then the value of ivalue is assigned to it If it was an object (of type struct/class) it would be initialised using default constructor, then assigned i.e. value would be set twice! 32

Initialisation vs Assignment (2) Compare the following: 1) int i = 4; // Initialisation 2) int j; // Uninitialised j = 4; // Assignment Initialisation lists are used a LOT in C++ Should be used in preference to member assignment Not available in Java! In Java you use super() to pass parameters to base class constructor, and then just assign values to members in the constructor In C++ you use the initialisation list for both Initialisation list can be faster in some cases Avoids work from an unnecessary default constructor 33

Member data initialisation Member data is NOT always initialised Basic types and pointers (e.g. int, short or char*) are NOT initialised You should always initialise them Default constructor is called for members of type class/struct unless you say otherwise (using initialisation list) BIG WARNING TO YOU!!!! (I am warning you because the compiler won t!) 34

Inline functions Member functions and data 35

Inline functions Inline functions act exactly like normal functions but no function call is made (code is put in caller function) Use the keyword inline, e.g.: inline int max( int a, int b ) { return a>b? a : b; } printf("%d\n", max(12,34) ); Similar to a safe macro expansion Safely replaces the function call with the code Unlike a macro (#define) Avoids the overhead of creating a stack frame Code gets included in EVERY file/function which calls it VERY useful for small, fast functions It is advice only: compiler can decide to ignore you 36

Function definitions outside the class IN professional code, member functions are usually defined outside of the class declaration In Java they are always defined within the class declaration, with one class per file In C++ you usually have: Function declaration inside class declaration Function definition somewhere else With a label to say it is a class member We use the scoping operator :: to label it Reason: allows hiding of the implementation Good program design, that Java s policy makes very hard to do Defining functions within the class declaration implicitly makes them inline As if they had inline on them 37

Class Declaration and Definition class DemoClass { public: DemoClass( int ivalue = -1 ) : m_ivalue(ivalue) { } ~DemoClass() { } These are all inline functions. Do not actually exist in executable as functions their code is included INLINE in the caller int GetValue() { return m_ivalue; } void SetValue(int ivalue) { m_ivalue = ivalue; } private: int m_ivalue; }; 38

Defining class member functions DemoClass.h class DemoClass { public: DemoClass ( int ivalue = -1 ); ~DemoClass(); int GetValue(); void SetValue( int ivalue); private: int m_ivalue; }; DemoClass.cpp #include "DemoClass.h" DemoClass::DemoClass ( int ivalue ) : m_ivalue(ivalue) { } DemoClass::~DemoClass() { } int DemoClass::GetValue() { return m_ivalue; } void DemoClass::SetValue( int ivalue ) { m_ivalue = ivalue; } 39

Note: Default value DemoClass.h class DemoClass { public: DemoClass ( int ivalue = -1 ); ~DemoClass(); int GetValue(); void SetValue( int ivalue); #include "DemoClass.h" DemoClass::DemoClass ( int ivalue ) : m_ivalue(ivalue) { } DemoClass.cpp Functions in C++ can have default values for parameters. Specify these in the function declaration, not the definition private: int m_ivalue; }; 40

Demo lecture Please try the coursework lab A BEFORE the demo lecture The coursework framework Class files and header files Function definitions outside the header file Constructors and destructors Initialisation list Inline functions Mainfunction.cpp Also, inheritance (single) base classes Base class : BaseGameEngine 41

Next lecture new and delete Inheritance Virtual functions 42