Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University"— Presentation transcript:

1 Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University hncharif@bournemouth.ac.uk http://ncca.bmth.ac.uk/hncharif/CP3

2 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 http://www.mindview.net/Books/DownloadSites Credits: 20 Grading: unfortunately only an Exam

3 Course Organization Study hours 180h Contact  Lectures: Two Hours Weekly  Supervised Labs: One Hour weekly Linkage: Major Project

4 Learning Outcomes An understanding of concepts & Techniques of Object Oriented Programming The ability to apply OOP through the use of C++

5 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

6 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++

7 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”

8 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 P1 int main(void)‏ { std::cout << “Hello World in ANSI C++” << endl; return 1 ; }

9 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 using namespace std; int main(void)‏ { cout << “Hello World in ANSI C++” << endl; return· ; }

10 namespace IV #include P2 using 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.95 11.21 17.56 54.84

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

12 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 header without the.h: #include 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)‏

13 More on strings #include P4 #include 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; }

14 the program's output Please enter your name Hammadi Please enter your age 42 Length of the string is 11 the strings are the same Hammadi 40 NCCA the strings are different

15 Reading a Whole Line #include P9 #include using namespace std; int main()‏ { cout << "Please enter a line:\n"; string s; getline(cin,s); cout << "You entered " << s << '\n'; }

16 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 = 0 A != B A == B The Output is

17 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 9 total = 45 Programs Output

18 Dynamic Memory Allocation int 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; }

19 Dynamic Memory Allocation II How big do you want your array 5 Enter myArray[0] = 54 Enter myArray[1] = 7 Enter myArray[2] = 96 Enter myArray[3] = 41 Enter myArray[4] = 32 54 7 96 41 32

20 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 2 nd has two parameters: int argc and char *argv[]. These are the only parameters that main is allowed

21 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.

22 A Simple Example Program #include P7 using 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 -t Arguments count = 5 argument-0 = argexample argument-1 = -c argument-2 = -l argument-3 = -m argument-4 = -t The Output

23 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

24 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

25 More on strings int 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; }

26 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

27 A simple getopt program #include // for printf P10 #include // for various unix defines #include //for getopt #include // for strcpy #include //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 program bool Verbose = false; bool Debug = false; bool Help = false; // the character returned from the getopt function char c; // now loop and parse the command line options while( (c=getopt(argc,argv,ARGUMENTS)) !=EOF)‏ {

28 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 exit printf("Unknown argument %c\n",optopt); printf("Valid arguments are -v -d -h \n"); printf("Will now exit\n"); exit(EXIT_FAILURE); break; }

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

30 Exercise (Lab session -1)‏ The program P10 is written in C Using this as a basis convert it to use C++ input and output

31 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

32 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

33 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.


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

Similar presentations


Ads by Google