c++ c++ overview (i) what is object orientated programming? approach: break problem into subgroups...
TRANSCRIPT
C++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
o Encapsulation: combine together code and data: data-hidingo Polymorphism: same interface, different ways of callingo 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++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)
C++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 used
in 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
C++Classes (II)
In file “andy.cpp”
Andy::Andy(){ age = 0;}
Andy::~Andy(){}
void Andy::setAge(int _age){ age = _age;}
int Andy::getAge(){ return age;}
Constructor function: calledwhenever an object of type
‘Andy’ is initialised
Destructor function: calledwhenever an ‘Andy’ object
goes 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
C++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
C++Classes (IV)
Construction and Destruction
Can have many different forms of constructorConstructor and destructor do NOT return a valueGood practice to supply an empty constructor
Object Assignment and passing to functions
The 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);
Andy();Andy(int);Andy(char*, int);
C++Arrays of objects (I)
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); }};
in file ‘element.h’
Two constructors: one is the ‘empty’ or‘default’ and the other takes two values
used to initialise private members
Function (aka method) defined in headerfile: called an ‘inline’ function
C++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 Element
constructed with initial values
Call ‘length’ methodAccess public ‘result’ variable
Call ‘length’ method thru pointer
C++Overloading (I)
o One function/method can take many formso Overloaded functions must all return same type of valueo 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);
C++Overloading (II)
o Overloading operators can change their meaningo Can overload any operatoro 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
C++Inheritance (I)
o One class can inherit the public data and methods of anothero Can build complexity thru using a hierarchyo Can access specialised classes thru a pointer to the base class
class Shape {public: int nvertex; Vertex* vertices;
Shape(int, Vertex*);
virtual draw();};
For instance, a square, a cross and a triangle are all shapes;they can all be represented using differing numbers of vertices
Create a base class called shape and derive different types
Data to represent any of thedifferent shape types
Base class constructor
‘virtual’ function is inherited
C++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}
Inheritance (II)
Call the base class constructorbefore constructing ‘Square’
Explicit drawing methods:different from each other
C++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();}..
Example: shape
Array of pointers to base class
‘new’ operator allocatesmemory for object and
returns pointer to it;pointer to ‘Cross’ is also
a pointer to ‘Shape’
The compiler works out which‘draw’ function to call
C++Template classes
o Templates are generic classes that offer particular functionalityo They ‘wrap’ around other classeso Standard template classes are available
#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”; }}
Header file from standard libraries
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
C++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++C++ Standard Libraries
#include <fstream.h>
Some slight confusion, courtesy of Microsoft (?)
#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
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
<cmath> = <math.h>
C++The ‘string’ class
o The standard string class is very useful; saves a lot of worko Many (library) functions require C strings (char*)o 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
C++Worked example: ‘finite’ (I)
Neighbour
‘this’ element
1) Create grid of elements dymanically2) Initialise elements – random values3) For each timestep:
Each element interacts mathematically with its 4 neighbours to find a result Output result from each element
4) Destroy memory used
Classes required:o Grid (to contain and process elements)o Element (to store result and data)o Index (to help find neighbours)
This element stores the addressesof its neighbouring elements
C++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();};
Pointer to neighbour
Some data
Result can be accessed directly
This method does the(daft) computation
Set ‘u’ and ‘v’ values
C++The End
Fortran
C++
The only way to learn a computer programming language is to program in it