object oriented programming in c++ dr. hammadi nait-charif media school bournemouth university...

33
Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University [email protected] http://ncca.bmth.ac.uk/hncharif/CP3

Upload: joella-cannon

Post on 28-Dec-2015

219 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Object Oriented Programming in C++

Dr. Hammadi Nait-CharifMedia School

Bournemouth University

[email protected]://ncca.bmth.ac.uk/hncharif/CP3

Page 2: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Overview

Prerequisite: Programming CP2 Text:

Object Oriented Programming with C++,

D. Parsons An Introduction to Object Oriented Programming,

Timothy A. Budd Thinking C++:

http://www.mindview.net/Books/DownloadSites Credits: 20 Grading: unfortunately only an Exam

Page 3: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Course Organization

Study hours 180h

Contact Lectures: Two Hours Weekly Supervised Labs: One Hour weekly

Linkage: Major Project

Page 4: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Learning Outcomes

An understanding of concepts & Techniques of Object Oriented Programming

The ability to apply OOP through the use

of C++

Page 5: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

C++

C++ is an extension of C

C++ was developed in early 1980s

C++ is an Object Oriented

programming language Programs are viewed as collection of

Objects

Objects have attributes and actions

Page 6: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

C++

C++ uses the same syntax as C, and adds extra elements to the core C language

All of the C programming elements are

still applicable

However we need to think in a

different way to design programs in C+

+

Page 7: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Namespaces I Almost all compilers allow the use of the

traditional header files

ANSI standard has completely redesigned

these libraries using templates features

All functions and variables are declared

under the namespace std

the new names for these “headers” are

basically the same for C++, but without

the “.h”

Page 8: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Namespaces II

The standard specified new names for the header files, basically the same as C, but without the “.h” for example iostream.h becomes iostream

#include <iostream> P1int main(void){ std::cout << “Hello World in ANSI C++” << endl;

return 1 ;}

Page 9: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Namespaces III In the previous example we used the std::

scope operator to load associate cout operator

using keyword introduces a name from a namespace into the current declarative region ==> no need for scope resolution operator#include <iostream>using namespace std;int main(void){ cout << “Hello World in ANSI C++” << endl;

return· ;}

Page 10: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

namespace IV#include <iostream> P2using namespace std;namespace vertex1{ double x = 8.95; double y = 11.21;}namespace vertex2{ double x = 54.84; double y = 17.56;}int main () { using namespace vertex1; cout << x << endl; cout << y << endl; cout << vertex2::y << endl; cout << vertex2::x << endl; return 0;}

Output

8.9511.2117.5654.84

Page 11: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Basic Input/Output standard output stream object cout uses the

operator (<<) to redirect text output to the screen

Handling the standard input is done by applying

the operator of extraction (>>) on the cin stream.

#include <iostream> P3

int main(void){ int age; std::cout << “Age ?”<< endl;//writes to standard output std::cin >> age ; //waits for an input from cin & store //it in age return 0 ;}

Page 12: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

The String Data Type

Good news: C++ has a string data type It is very powerful and has many functions built into

it

We include <string> header without the .h:

#include<string>

In C++ program we declare variables when we

need them not at the top of the function

(although we should declare them at the top if

possible)

Page 13: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

More on strings#include<iostream> P4#include<string>using namespace std;int main(){ cout << “Please enter your name “ << endl; string Name, Age, NameAge; cin >> Name; cout << “Please enter your age “ << endl; cin >> Age; string NameAge = Name + “ “ + Age; cout << “Length of the string is “ << NameAge.length()<< endl; string Test = NameAge; if(NameAge == Test) cout << “the strings are the same“ << endl; else cout << “the strings are different” << endl; Test += “ another bit “; cout << Test << endl; if(NameAge == Test) cout << “the strings are the same “ << endl; else cout << “ the strings are different”; return 1;}

Page 14: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

the program's output

Please enter your nameHammadiPlease enter your age42Length of the string is 11the strings are the sameHammadi 40 NCCAthe strings are different

Page 15: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Reading a Whole Line

#include<iostream> P9#include<string>using namespace std;

int main(){

cout << "Please enter a line:\n"; string s; getline(cin,s); cout << "You entered " << s << '\n';

}

Page 16: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Bool C++ gives us a boolean data type which

can be set to either true or false

int main() P5{ bool A=true; bool B=false; cout << “A= “ << A <<“ & B = “ << endl; if(A==B) cout << “A == B” << endl; else cout << “A != B” << endl; A = B; if(A==B) cout << “A == B” << endl; else cout << “A != B” << endl; return 1;}

A= 1 & B = 0A != BA == B

The Output is

Page 17: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Local Variable Scope

It is possible to declare variables whenever we want

For example it is common to declare a

variable within the loop

int main(){ int total=0; for(int i=0; i<10; i++) { total += a; cout << “ “ << i ; } cout<<endl << “total = “<< total << endl;}

0 1 2 3 4 5 6 7 8 9total = 45

Programs Output

Page 18: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Dynamic Memory Allocationint main() P6{ int *myArray; int arraysize; cout << “How big do you want your array << endl; cin >> arraysize; // now allocate space for the array myArray = new int[arraysize]; for(int i=0; i<arraysize; i++) { cout << “Enter myArray[“<< i <<”] =”; cin >> myArray[i]; } for(int i=0; i<arraysize; i++) cout << “myArray[“<< i << “] =” << myArray[i]<<endl;

// finally we delete the array delete [] myArray; return 1;}

Page 19: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Dynamic Memory Allocation II

How big do you want your array 5Enter myArray[0] = 54Enter myArray[1] = 7Enter myArray[2] = 96Enter myArray[3] = 41Enter myArray[4] = 32547964132

Page 20: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Command Line Argument

the main() function is the entry point in any C++ program and may be declared in a number of ways:

int main(void)int main(int argc, char *argv[])

the first returns an integer when the program exits

The 2nd has two parameters: int argc

and char *argv[]. These are the only

parameters that main is allowed

Page 21: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Command Line Argument

int argc is the argument count: the number of arguments passed at the command line

char *argv[] is a pointer to a list of command line arguments which may be accessed as of they were a series of things.

Page 22: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

A Simple Example Program

#include<iostream> P7using namespace std;int main(int argc, char *argv[]){ cout << “Arguments count=”<< argc <<endl; for(int i=0;i<argc; i++) cout << “argument-”<<i<<” = “<<argv[i]<<endl; return 1; }

argexample -c -l -m -tArguments count = 5argument-0 = argexampleargument-1 = -cargument-2 = -largument-3 = -margument-4 = -t

The Output

Page 23: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

A Simple Example Program

The first argument argv[0] prints as argexample

this is because the whole of the command line typed is passed into the program

when the program is executed the command line is placed into argv array element

Finally the size of the argv array is placed into argc

Page 24: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Parsing Command line arguments

The following program parses the command line to find one of three flags. These are -mode1, -mode2 and -help.

The mode flags both accept further parameters but help does not

Finally an incorrect parameter causes the program to exit

Page 25: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

More on stringsint main(int argc, char *argv[]){ int argcount = 1; //*argv[1] is the first parameter int mode; while(argcount<argc) { string Argument(argv[argcount]); if(Argument == “-mode1”) { argcount++; cout << “mode 1 parameter = “<< argv[argcount++] << endl; mode = 1; } else if(Argument == “-mode2”) { argcount++; cout << “mode 2 parameter = “<< argv[argcount++] << endl; mode = 2; } else if (Argument == “-help”) { argcount++; cout << “Help mode “ << endl; } else { cout << “unkown argument” << endl; exit(1); } } cout << “End of the Program in mode”<<mode << endl;return 1;}

Page 26: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Using getopt

As you can see we have to write a bit of parsing code each time we add new options which is a pain

However, the standard unix C library

contains a function to help us to deal with

command line arguments: An element of argv that starts with ‘-’ (and

is not exactly "-" or "--") is an option

element. man 3 getopt to find more on linux

Page 27: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

A simple getopt program

#include <stdio.h> // for printf P10#include <unistd.h> // for various unix defines#include <stdlib.h> //for getopt#include <string.h> // for strcpy #include <stdbool.h> //for bool and true false// define the command line argument parameters:indicates 2nd arg#define ARGUMENTS "vdh"int main(int argc, char *argv[]){// define some inital global variables for the programbool Verbose = false;bool Debug = false;bool Help = false;

// the character returned from the getopt functionchar c;// now loop and parse the command line optionswhile( (c=getopt(argc,argv,ARGUMENTS)) !=EOF) {

Page 28: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

switch(c) // which option has been chosen {

case 'v' : // -v  printf("Setting Verbose Mode\n");Verbose = true;

break;case 'd' : // -d

printf("Setting Debug Mode\n");Debug = true;

break;case 'h' : //-h

printf("Help Mode\n");Help=true;

break;

case '?' : // unknown option report this and exitprintf("Unknown argument %c\n",optopt);printf("Valid arguments are -v -d -h \n");printf("Will now exit\n");exit(EXIT_FAILURE);

break;}

Page 29: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

}printf("Argument parsed current modes are as follows\n");printf("Debug = %d\n",Debug);printf("Verbose = %d\n",Verbose);printf("Help = %d\n",Help);return EXIT_SUCCESS;}

Page 30: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Exercise (Lab session -1)

The program P10 is written in C Using this as a basis convert it to use

C++ input and output

Page 31: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Compiling a C++ Program To compile with the gnu C++ compiler use

shell and issue the following commands

g++ -Wall -g Hello.cpp -o Hello

What does that say?g++ is the name of the compiler

-Wall Print all Warnings

-g Add debug information (so we can use the integrated debuggers)

-o Output to executable named [in this case Hello] If this option is not included the default a.out is used

Page 32: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

Other g++ options

There are many other options to g++ most of the ones we will use are to do with either paths or optimisations

Path Options are as follows-I (capital i) specifies a path to search for an Include file e.g.

-I /home/GraphicsLib/include

-L specifies a path to search for Libraries. e.g. -L/usr/local/lib

To include other libraries we use the following option -lGraphicsLib -lglut

To include a library it must be in a location the

compiler can find specified by the -L option

Page 33: Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk

g++ Compiler Optimization

There are a number of optimizations which make your code faster, the main one are as follows

-funroll-loops unrolls loops and makes code execution faster (but program size bigger)

-O3 There are a number of different optimisation level O3 being the highest

-ffast-math This version removes error checking from the maths lib (no reporting of errors)

Use the g++ man pages to find more info on

these options.