Top Banner
Advanced Advanced Programming Programming Introduction to C++ Introduction to C++
49

Click to add Text Advanced Programming Introduction to C++

Jan 13, 2016

Download

Documents

Edwin Patterson
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Click to add Text Advanced Programming Introduction to C++

Advanced ProgrammingAdvanced ProgrammingIntroduction to C++Introduction to C++

Page 2: Click to add Text Advanced Programming Introduction to C++

IntroductionIntroduction

• Who am I?Who am I?• What am I doing?What am I doing?• Where’s Mandla???Where’s Mandla???• What I hope to accomplish?What I hope to accomplish?• Class repClass rep• http://advancedprogrammingmirror.pbworks.comhttp://advancedprogrammingmirror.pbworks.com

Page 3: Click to add Text Advanced Programming Introduction to C++

Course outlineCourse outline

Page 4: Click to add Text Advanced Programming Introduction to C++

Learning outcomesLearning outcomes

Page 5: Click to add Text Advanced Programming Introduction to C++

AssessmentAssessment

Page 6: Click to add Text Advanced Programming Introduction to C++

ScheduleSchedule

Week 1Week 1• Getting used to using C++Getting used to using C++• Assignments issued (Friday)Assignments issued (Friday)

Week 2Week 2• Introducing aspects C++ has that Java Introducing aspects C++ has that Java

does not.does not.• Introduction to OpenGL (Thursday lecture)Introduction to OpenGL (Thursday lecture)

Page 7: Click to add Text Advanced Programming Introduction to C++

ScheduleSchedule

Week 3Week 3• Arrays and stringsArrays and strings• Pointers and dynamic memoryPointers and dynamic memory• 2D in OpenGL 2D in OpenGL Week 4Week 4• Inheritance and PolymorphismInheritance and Polymorphism• Design patternsDesign patterns• Standard Template Library – Sequential Standard Template Library – Sequential

containerscontainers• Test 1 (Thursday the 5Test 1 (Thursday the 5thth of March) of March)

Page 8: Click to add Text Advanced Programming Introduction to C++

Test 1Test 1

• Syntax checkingSyntax checking• Error identificationError identification• Code correctionCode correction• Solving a problemSolving a problem• Code identificationCode identification• Pointers will not be testedPointers will not be tested

Page 9: Click to add Text Advanced Programming Introduction to C++

Test 2Test 2

• Will consist of pretty much anythingWill consist of pretty much anything• Will focus on problem solving using C++Will focus on problem solving using C++• Will be pretty much exam preparationWill be pretty much exam preparation

Page 10: Click to add Text Advanced Programming Introduction to C++

PracticalsPracticals

• First 2 weeks will focus on converting First 2 weeks will focus on converting between Java and C++between Java and C++

• From the second week there will always From the second week there will always be an OpenGL ‘task’be an OpenGL ‘task’

• Practicals will feature design patterns and Practicals will feature design patterns and concepts related to Game Programmingconcepts related to Game Programming

• Before you are taught, you will use magic Before you are taught, you will use magic things!things!

Page 11: Click to add Text Advanced Programming Introduction to C++

Programming languagesProgramming languages

C-1972 BASIC-1964 Lisp-1958 Haskell-1990 Python-1991 Java-1991 C++-1983

Language Imperative OOP Functional Procedural Generic Reflective Event driven

C Yes     Yes      

C# Yes Yes Yes Yes Yes Yes Yes

Lisp Yes Yes Yes Yes   Yes Yes

Python Yes Yes Yes     Yes  

Haskell     Yes   Yes    

Java Yes Yes     Yes Yes  

C++ Yes Yes Yes Yes Yes    

Page 12: Click to add Text Advanced Programming Introduction to C++

C++ vs C vs C#C++ vs C vs C#

Page 13: Click to add Text Advanced Programming Introduction to C++

C++ vs BasicC++ vs Basic

Page 14: Click to add Text Advanced Programming Introduction to C++

C++ vs LispC++ vs Lisp

Page 15: Click to add Text Advanced Programming Introduction to C++

C++ vs HaskellC++ vs Haskell

Page 16: Click to add Text Advanced Programming Introduction to C++

C++ vs PythonC++ vs Python

Page 17: Click to add Text Advanced Programming Introduction to C++

C++ vs JavaC++ vs Java

Page 18: Click to add Text Advanced Programming Introduction to C++

What the hell is cout???What the hell is cout???

• It’s an object!It’s an object!• It is staticIt is static• << – Uses the insertion operator<< – Uses the insertion operator• >> – cin uses the extraction operator>> – cin uses the extraction operator

Page 19: Click to add Text Advanced Programming Introduction to C++

Programming ParadigmsProgramming Paradigms

FunctionalFunctional Haskell: fibonacci2 Haskell: fibonacci2 == 0 0::11:zipWith:zipWith ( (++) fibonacci2 () fibonacci2 (tailtail

fibonacci2) fibonacci2)

Object orientatedObject orientated C++, Java, SmallTalk, C#, Visual BasicC++, Java, SmallTalk, C#, Visual Basic

DeclarativeDeclarative ProceduralProcedural Logic and symbolicLogic and symbolic

LispLisp PrologProlog

Page 20: Click to add Text Advanced Programming Introduction to C++

C++ C++

Strong typingStrong typing SyntaxSyntax

Own vocabulary (keywords) e.g.Own vocabulary (keywords) e.g. class, for, while, includeclass, for, while, include … …

Case sensitiveCase sensitive Using Using ForFor instead of instead of forfor will not work! will not work!

SemanticsSemantics cout << “Hello World”;cout << “Hello World”; Means display the text Means display the text Hello WorldHello World on the screen. on the screen.

Page 21: Click to add Text Advanced Programming Introduction to C++

C++ UsesC++ Uses

Operating systemsOperating systems Game developmentGame development CADCAD Influenced PHP, LUA, Java, C# and PerlInfluenced PHP, LUA, Java, C# and Perl Firefox!Firefox!

Page 22: Click to add Text Advanced Programming Introduction to C++

C++ ProgramsC++ Programs

What is the difference between version 2 What is the difference between version 2 and version 3?and version 3?

Page 23: Click to add Text Advanced Programming Introduction to C++

#Includes#Includes #include <iostream>#include <iostream>

Gives you access to stream operatorsGives you access to stream operators Allows for basic input and output to consoleAllows for basic input and output to console cout << allows inputcout << allows input cin >> allows outputcin >> allows output

#include <string>#include <string> Gives you access to the type stringGives you access to the type string Why isn't string native to C++?Why isn't string native to C++?

#include “myfilename.h”#include “myfilename.h” For including your own headersFor including your own headers

#include <externallibfile.h>#include <externallibfile.h> For including external library headersFor including external library headers

Page 24: Click to add Text Advanced Programming Introduction to C++

C++ ProgramsC++ Programs

• Program extensions: .cc Program extensions: .cc .cpp.cpp .cxx .c .c+ .cxx .c .c++ + 

• Header extensions Header extensions .h.h .hh . .hh .hpphpp .hxx .h++ .hxx .h++ • Must always have a main programMust always have a main program• Low level language (Low level language (Only .asm is closer to the hardware!Only .asm is closer to the hardware!))

Page 25: Click to add Text Advanced Programming Introduction to C++
Page 26: Click to add Text Advanced Programming Introduction to C++

C++ Preprocessor, Compiler and C++ Preprocessor, Compiler and LinkingLinking

• Preprocessor dictates what needs to Preprocessor dictates what needs to happen before compilationhappen before compilation

• Compiler will output object files (.o) Compiler will output object files (.o) • Linking will join all the object files and Linking will join all the object files and

external libraries that are requested external libraries that are requested togethertogether

Page 27: Click to add Text Advanced Programming Introduction to C++

C++ ErrorsC++ Errors

• Compile errorCompile error– Forgetting a ;Forgetting a ;

– Forgetting a }Forgetting a }

• Linker errorLinker error– No implementation of function from headerNo implementation of function from header

– Library not linked toLibrary not linked to

• Logical errorLogical error– whilewhile( x = a) (where x and a are strings)( x = a) (where x and a are strings)

• Undefined Undefined behaviourbehaviour

Page 28: Click to add Text Advanced Programming Introduction to C++

The C++ compilation processThe C++ compilation process

Page 29: Click to add Text Advanced Programming Introduction to C++

Compiling C++Compiling C++• Open the terminalOpen the terminal• Create a file myprogram.cppCreate a file myprogram.cpp• Write a main functionWrite a main function• Go to the correct directoryGo to the correct directory• Enter: g++ -c myprogram.cppEnter: g++ -c myprogram.cpp• This will create an object file: myprogram.oThis will create an object file: myprogram.o• g++ -g -c myprogram.cpp – will generate debugging informationg++ -g -c myprogram.cpp – will generate debugging information• -L – Library paths-L – Library paths

-l – Libraries-l – Libraries-v – Verbose mode-v – Verbose mode

• See for details: See for details: https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.htmlhttps://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html

• http://pages.cs.wisc.edu/~beechung/ref/gcc-intro.htmlhttp://pages.cs.wisc.edu/~beechung/ref/gcc-intro.html

Page 30: Click to add Text Advanced Programming Introduction to C++

C++ differences to JavaC++ differences to Java

An example of if and elseAn example of if and else void main() { int a_number = 0; cout << "Enter a number :\t"; cin >> a_number; if (a_number < 0) { cout << a_number << " is negative"; } else { cout << a_number << " is positive"; } }

Page 31: Click to add Text Advanced Programming Introduction to C++

C++ differences to JavaC++ differences to Java

• Java runs everywhere using interpreted byte Java runs everywhere using interpreted byte codecode

• C++ compiles anywhere but only runs on the C++ compiles anywhere but only runs on the system it was compiled forsystem it was compiled for

• C++ supports unsigned arithmetic, no need for C++ supports unsigned arithmetic, no need for BigInteger.BigInteger.

• C++ generally requires you to allocate and C++ generally requires you to allocate and deallocate your memory usage.deallocate your memory usage.

• C++ is not bloated, there is no GUI built in.C++ is not bloated, there is no GUI built in.• C++ can use stand alone functionsC++ can use stand alone functions

Page 32: Click to add Text Advanced Programming Introduction to C++

VariablesVariables

• The type char is 8bits in C++, in Java it is The type char is 8bits in C++, in Java it is 16 bits16 bits

• You can check size using sizeof(TYPE) You can check size using sizeof(TYPE) • sizeof(float) = 4 and sizeof(double) = 8 sizeof(float) = 4 and sizeof(double) = 8

Page 33: Click to add Text Advanced Programming Introduction to C++

OperatorsOperators

• >> – signed right bit shift – Overloaded for iostream>> – signed right bit shift – Overloaded for iostream• << – signed left bit shift – Overloaded for iostream<< – signed left bit shift – Overloaded for iostream• sizeofsizeof• :: – scope operator:: – scope operator• -> Used with Pointers in place of the . Operator-> Used with Pointers in place of the . Operator• . Access member operator. Access member operator• ==

– This performs assignmentThis performs assignment– A common mistake is to use = instead of == in an if statementA common mistake is to use = instead of == in an if statement

Page 34: Click to add Text Advanced Programming Introduction to C++

Bit operatorsBit operators

operator asm equivalent description

& AND Bitwise AND

| OR Bitwise inclusive OR

^ XOR Bitwise exclusive OR

~ NOT Unary complement (bit inversion)

<< SHL Shift bits left

>> SHR Shift bits right

Page 35: Click to add Text Advanced Programming Introduction to C++

CastingCasting

• You can cast between types the same as in JavaYou can cast between types the same as in Java

• However C++ makes use of more specific castsHowever C++ makes use of more specific casts

• static_cast<TYPE> (variable)static_cast<TYPE> (variable)

• dynamic – turn a child into a parent classdynamic – turn a child into a parent class

• const–adds or removes const from a variable const–adds or removes const from a variable

• reinterpret–turn a cat into a pigeon but ‘can’ turn back reinterpret–turn a cat into a pigeon but ‘can’ turn back into a catinto a cat

Page 36: Click to add Text Advanced Programming Introduction to C++

Comparison operatorsComparison operators

Operator Meaning

== equal to

!= not equal to

< less than

<= less than or equal to

> greater than

>= greater than or equal to

&& means AND || means OR

Page 37: Click to add Text Advanced Programming Introduction to C++

Header filesHeader files

• Tell us what to compileTell us what to compile• Specify the order of operationsSpecify the order of operations• Cyclical referencing – Be carefulCyclical referencing – Be careful• Allows a function to be known by another Allows a function to be known by another

classclass

Page 38: Click to add Text Advanced Programming Introduction to C++

C++ Hello World with a ClassC++ Hello World with a Class

Page 39: Click to add Text Advanced Programming Introduction to C++

C++ Hello World with a ClassC++ Hello World with a Class

Page 40: Click to add Text Advanced Programming Introduction to C++

C++ Hello World with a ClassC++ Hello World with a Class

Page 41: Click to add Text Advanced Programming Introduction to C++

Namespaces Namespaces

• A namespace adds a A namespace adds a scope to your classscope to your class

• Multiple classes can Multiple classes can be in the same be in the same namespacenamespace

• A Namespace A Namespace removes ambiguityremoves ambiguity

• The command The command using using namespace namespace stdstd; ; COULD cause an COULD cause an issue.issue.

Page 42: Click to add Text Advanced Programming Introduction to C++

ScopeScope

• PublicPublic– The data type The data type structstruct is by default PUBLIC is by default PUBLIC

• PrivatePrivate– The data type The data type classclass is by default PRIVATE is by default PRIVATE

• ProtectedProtected– Inheritance relatedInheritance related– Let’s the child class use parent membersLet’s the child class use parent members

Page 43: Click to add Text Advanced Programming Introduction to C++

The C libraryThe C library

• Still usefulStill useful• cstdio <stdio.h>cstdio <stdio.h>

– printf, snprintfprintf, snprintf– scanfscanf

• cmath <math.h>cmath <math.h>• cstdlib <stdlib.h>cstdlib <stdlib.h>

– There are better ways in C++ to do most of There are better ways in C++ to do most of what is done here!what is done here!

Page 44: Click to add Text Advanced Programming Introduction to C++

The C++ libraryThe C++ library

• Sequential containersSequential containers– vector<type> similar to java’s ArrayList vector<type> similar to java’s ArrayList – list<type>list<type>

• Associative containersAssociative containers– map<key, value>map<key, value>– multimapmultimap

• AlgorithmsAlgorithms• Streams and input/outputStreams and input/output

– <fstream><fstream>– <sstream><sstream>

Page 45: Click to add Text Advanced Programming Introduction to C++

MemoryMemory

ProcessesProcesses OS is first process loadedOS is first process loaded OS manages the loading of OS manages the loading of

subsequent processes subsequent processes

multiple processes can be multiple processes can be loaded at the same timeloaded at the same time

processes are loaded in lowest processes are loaded in lowest RAM address space availableRAM address space available

all memory above the highest all memory above the highest process is called the heapprocess is called the heap

Page 46: Click to add Text Advanced Programming Introduction to C++

Memory allocationMemory allocation

CODECODE compiler executable codecompiler executable code

DATADATA globally declared variablesglobally declared variables

STACKSTACK local variables & parameterslocal variables & parameters return addressreturn address usage varies during program usage varies during program

executionexecution

DATA + STACKDATA + STACK maximum 1Mb (default)maximum 1Mb (default)

Page 47: Click to add Text Advanced Programming Introduction to C++

RecommendationsRecommendations

• Try as many things as possibleTry as many things as possible– You will need to make mistakes to be able to You will need to make mistakes to be able to

identify error messages!identify error messages!

• Open and or use a drop box accountOpen and or use a drop box account• Keep it simpleKeep it simple

Page 48: Click to add Text Advanced Programming Introduction to C++

C and C++ KeywordsC and C++ Keywords

C++ keywordsC++ keywordsC++ keywords.

C++ Keywords

Keywords common to the C and C++ programming languages

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while      

Page 49: Click to add Text Advanced Programming Introduction to C++

C++ keywordsC++ keywordsC++-only keywords

and and_eq asm bitand bitor

bool catch class compl const_cast

delete dynamic_cast explicit export false

friend inline mutable namespace new

not not_eq operator or or_eq

private protected public reinterpret_cast static_cast

template this throw true try

typeid typename using virtual wchar_t

xor xor_eq