200 likes | 421 Views
C++ Overview (I). What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that take into account code and data; organise subgroups into hierarchy; translate to objects…. Objects Encapsulation: combine together code and data: data-hiding
E N D
C++ Overview (I) What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that takeinto account code and data; organise subgroups into hierarchy;translate to objects… • Objects • Encapsulation: combine together code and data: data-hiding • Polymorphism: same interface, different ways of calling • Inheritance: derive specific objects from more general ones An object is defined by a class; the class combines data and methods;a class defines a new data type… think in objects!
C++ Overview (II) Function overloading A function can represent a concept (e.g. set_value) but it may becalled with different types of data – the compiler sorts out whichvariant of set_value to call Operator overloading Any of the operators in C++ (e.g. ‘+’) can be redefined; a classcan define how ‘+’ operates on objects defined by the class Inheritance For a group of related concepts (e.g. types of buildings) extractcommon functionality and data into a base class (e.g. building)and derive more specific classes (e.g. house, garage, hotel)
Classes (I) In general, a class is declared in a header file and defined in asource file; #include the header file wherever the class is usedin file “andy.h”class Andy {private: int age;public: Andy(); ~Andy(); void setAge(int); int getAge();}; Name of class and new data type Until otherwise specified, declarations canonly be accessed by methods of class ‘Andy’ Specify that declarations can be accessedby any part of the program A function that returns an integer:a method of class ‘Andy’ Note the semi-colon
Classes (II) In file “andy.cpp” Constructor function: calledwhenever an object of type‘Andy’ is initialised Andy::Andy(){ age = 0;}Andy::~Andy() {} void Andy::setAge(int _age){ age = _age;} int Andy::getAge(){ return age;} Destructor function: calledwhenever an ‘Andy’ objectgoes out of scope (or is deleted) ‘age’ is a private member of class ‘Andy’so must be accessed by a class method ‘::’ is the scope operator; need to tell thecompiler we are defining ‘getAge’ in class‘Andy’ – no ‘::’ means function is not aclass method
Classes (III) in file ‘main.cpp’#include <iostream.h> #include “andy.h”.. Andy andy1, andy2; Andy* andyPtr = 0; andy1.setAge(1); andy2.setAge(99); andyPtr = &andy2; cout << “Andy is aged “ << andy1.getAge() << “ or “ << andyPtr->getAge() << “\n”;.. Variables are declared in just the sameway as if they were, say, integers Call methods on objects using the‘.’ operator (just like structs) Call methods through a pointer toan object by using ‘->’ operator;just like with structs
Classes (IV) Construction and DestructionCan have many different forms of constructorConstructor and destructor do NOT return a valueGood practice to supply an empty constructor Andy(); Andy(int); Andy(char*, int); Object Assignment and passing to functionsThe compiler automatically does a bitwise copy if an object isassigned (‘=‘) to another object or used as an argument to afunction – can override the automatic behaviour… Andy a, b;a.setAge(10);b = a; cout << b.getAge(); void func(Andy aaa);Andy a;func(a);
Arrays of objects (I) in file ‘element.h’ class Element {private: double u, v; public: double result; Element() : u(0.0), v(0.0) {} Element(double _u, double _v) : u(_u), v(_v) {} double length() { return sqrt(u*u + v*v); }}; Two constructors: one is the ‘empty’ or‘default’ and the other takes two valuesused to initialise private members Function (aka method) defined in headerfile: called an ‘inline’ function
Arrays of objects (II) int j;Element* elem = new Element[100];for (j=0; j<100; j++) { elem[j] = Element(1.0, 0.5); }for (j=0; j<100; j++) { double len = elem[j].length(); double res = elem[j].result;}Element* ptr = elem;for (j=0; j<100; j++) { double len = ptr->length(); elem++;} Make new copy of elem[j] byassignment from Elementconstructed with initial values Call ‘length’ methodAccess public ‘result’ variable Call ‘length’ method thru pointer
Overloading (I) • One function/method can take many forms • Overloaded functions must all return same type of value • Compiler decides which form of function to call class Andy {private: double dVal; float fVal; int iVal;public: void setData(double val) { dVal = val; } void setData(float val) { fVal = val; } void setData(int val) { iVal = val; } }; Andy a;a.setData(1.0f);a.setData(42);
Overloading (II) • Overloading operators can change their meaning • Can overload any operator • Makes for easy to read code Class Vector {private: double a, b;public: Vector() : a(0.0), b(0.0) {} Vector(double _a, double _b) : a(_a), b(_b) {} Vector operator+(Vector x) { return Vector(a+x.a, b+x.b); } }; Vector u(2.0, -2.0), v(-1.0, 1.0), w;w = u + v; ‘+’ operator method of u is calledwith v as the function argument
Inheritance (I) • One class can inherit the public data and methods of another • Can build complexity thru using a hierarchy • Can access specialised classes thru a pointer to the base class For instance, a square, a cross and a triangle are all shapes;they can all be represented using differing numbers of verticesCreate a base class called shape and derive different types class Shape {public: int nvertex; Vertex* vertices; Shape(int, Vertex*); virtual draw();}; Data to represent any of thedifferent shape types Base class constructor ‘virtual’ function is inherited
Inheritance (II) class Square : public Shape {public: Square(Vertex* _v) : Shape(4, _v) {} void draw();};void Square::draw(){ // draw a line loop thru all vertices} class Cross : public Shape {public: Triangle(Vertex* _v) : Shape(4, _v) {} void draw();};void Cross::draw(){ // draw 2 lines, connecting opposite vertices} Call the base class constructorbefore constructing ‘Square’ Explicit drawing methods:different from each other
Inheritance (III) . . // declare the Vertex data for each type of shape . . Shape* shapes[4];shapes[0] = new Cross(crossData);shapes[1] = new Square(squareData);shapes[2] = new Triangle(triangleData);shapes[3] = new Hexagon(hexagonData);for (int j=0; j<4; j++) { Shape* ptr = shapes[j]; ptr->draw();} . . Array of pointers to base class ‘new’ operator allocatesmemory for object andreturns pointer to it;pointer to ‘Cross’ is alsoa pointer to ‘Shape’ The compiler works out which‘draw’ function to call Example: shape
Template classes • Templates are generic classes that offer particular functionality • They ‘wrap’ around other classes • Standard template classes are available Header file from standard libraries #include <list.h>..list<int> listOfInts;listOfInts.push_back(4);.. listOfInts.sort();list<int>::iterator iter;for (iter=listOfInts.begin(); iter!=listOfInts.end(); iter++) { if (*iter == 4) { cout << “found it!\n”; } } Specify what we want a list of Add something to the list ‘list’ class uses ‘<‘ and ‘>’ operatorsof ‘int’ to order the list Processing thru the list
Array based I/O Frequently need to write variables into a character string #include <strstrea.h>#include <fstream.h>char cstring[80]; int filenumber = 11; ostrstream ostr(cstring, 80);ostr << “datafile” << filenumber << “.dat” << ends;// now can use cstring to open a fileofstream ofile;ofile.open(cstring); // opens a file named “datafile11.dat” ostrstream object usescstring as a buffer Write into ‘ostr’ in thesame way as to thescreen or to a file ‘ends’ adds a ‘\0’ to theend of the C string
C++ Standard Libraries Some slight confusion, courtesy of Microsoft (?) #include <fstream.h> #include <fstream> using namespace std; You are allowed to use thistype of header (*.h) sometimes You should use this type,but need to add the ‘using’line after one or more includes <cmath> = <math.h> Main standard header files are: <algorithm>, <climits>, <cmath>, <cstdlib>,<fstream>, <iostream>, <list>, <string>, <strstream> There are lots more: see “Library, Standard C++” in MSDN index You can include C headers (and use C functions) in C++ programs
The ‘string’ class • The standard string class is very useful; saves a lot of work • Many (library) functions require C strings (char*) • The string class can be used to manipulate and create C strings #include <string>using namespace std;..string s1(“C++ is my friend”);string s2 = “Andy”;string s3;s3 = s2 + “, “ + s1;char* cs1 = s3.c_str();.. Other methods of class stringinclude finding sub-strings,getting string length, ==, <,>, != and lots more…See “string” and “basic_string”in the MSDN documentation
Worked example: ‘finite’ (I) • Create grid of elements dymanically • Initialise elements – random values • For each timestep: Each element interacts mathematically with its 4 neighbours to find a result Output result from each element • Destroy memory used ‘this’ element Neighbour • Classes required: • Grid (to contain and process elements) • Element (to store result and data) • Index (to help find neighbours) This element stores the addressesof its neighbouring elements
Worked example: ‘finite’ (II) class Element { private: double u, v; Element* leftElemPtr; Element* rightElemPtr; Element* aboveElemPtr; Element* belowElemPtr; public: double result; Element(); ~Element() {} void addNeighbours(Element*, Element*, Element*, Element*); void init(double, double); void update(); void normalise(); double length(); double sumOfParts(); }; Some data Pointer to neighbour Result can be accessed directly Set ‘u’ and ‘v’ values This method does the(daft) computation
The End C++ Fortran The only way to learn a computer programming language is to program in it