Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University...

Post on 28-Dec-2015

220 views 3 download

Tags:

transcript

Object Oriented Programming in C++

Dr. Hammadi Nait-CharifMedia School

Bournemouth University

hncharif@bournemouth.ac.ukhttp://ncca.bmth.ac.uk/hncharif/CP3

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

Course Organization

Study hours 180h

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

Linkage: Major Project

Learning Outcomes

An understanding of concepts & Techniques of Object Oriented Programming

The ability to apply OOP through the use

of C++

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

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+

+

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”

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 ;}

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· ;}

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

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 ;}

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)

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;}

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

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';

}

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

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

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;}

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

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

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.

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

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

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

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;}

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

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) {

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;}

}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;}

Exercise (Lab session -1)

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

C++ input and output

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

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

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.