Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ C++ Overview (I) What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that take into account code and data;

Similar presentations


Presentation on theme: "C++ C++ Overview (I) What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that take into account code and data;"— Presentation transcript:

1 C++ 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 o Encapsulation: combine together code and data: data-hiding o Polymorphism: same interface, different ways of calling o 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!

2 C++ C++ Overview (II) Function overloading A function can represent a concept (e.g. set_value) but it may be called with different types of data – the compiler sorts out which variant of set_value to call Operator overloading Any of the operators in C++ (e.g. ‘+’) can be redefined; a class can define how ‘+’ operates on objects defined by the class Inheritance For a group of related concepts (e.g. types of buildings) extract common functionality and data into a base class (e.g. building) and derive more specific classes (e.g. house, garage, hotel)

3 C++ Classes (I) In general, a class is declared in a header file and defined in a source 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 can only be accessed by methods of class ‘Andy’ Specify that declarations can be accessed by any part of the program A function that returns an integer: a method of class ‘Andy’ Note the semi-colon

4 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: called whenever an object of type ‘Andy’ is initialised Destructor function: called whenever 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 the compiler we are defining ‘getAge’ in class ‘Andy’ – no ‘::’ means function is not a class method

5 C++ Classes (III) in file ‘main.cpp’ #include #include “andy.h”.. Andy andy1, andy2; Andy* andyPtr = 0; andy1.setAge(1); andy2.setAge(99); andyPtr = &andy2; cout getAge() << “\n”;.. Variables are declared in just the same way as if they were, say, integers Call methods on objects using the ‘.’ operator (just like structs) Call methods through a pointer to an object by using ‘->’ operator; just like with structs

6 C++ Classes (IV) Construction and Destruction Can have many different forms of constructor Constructor and destructor do NOT return a value Good practice to supply an empty constructor Object Assignment and passing to functions The compiler automatically does a bitwise copy if an object is assigned (‘=‘) to another object or used as an argument to a function – 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);

7 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 header file: called an ‘inline’ function

8 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 length(); elem++; } Make new copy of elem[j] by assignment from Element constructed with initial values Call ‘length’ method Access public ‘result’ variable Call ‘length’ method thru pointer

9 C++ Overloading (I) o One function/method can take many forms o Overloaded functions must all return same type of value o 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);

10 C++ Overloading (II) o Overloading operators can change their meaning o Can overload any operator o 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 called with v as the function argument

11 C++ Inheritance (I) o One class can inherit the public data and methods of another o Can build complexity thru using a hierarchy o 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 the different shape types Base class constructor ‘virtual’ function is inherited

12 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 constructor before constructing ‘Square’ Explicit drawing methods: different from each other

13 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 draw(); }. Example: shapeshape Array of pointers to base class ‘new’ operator allocates memory 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

14 C++ Template classes o Templates are generic classes that offer particular functionality o They ‘wrap’ around other classes o Standard template classes are available #include.. list listOfInts; listOfInts.push_back(4);.. listOfInts.sort(); list ::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 ‘ ’ operators of ‘int’ to order the list Processing thru the list

15 C++ Array based I/O Frequently need to write variables into a character string #include #include char cstring[80]; int filenumber = 11; ostrstream ostr(cstring, 80); ostr << “datafile” << filenumber << “.dat” << ends; // now can use cstring to open a file ofstream ofile; ofile.open(cstring); // opens a file named “datafile11.dat” ostrstream object uses cstring as a buffer Write into ‘ostr’ in the same way as to the screen or to a file ‘ends’ adds a ‘\0’ to the end of the C string

16 C++ C++ Standard Libraries #include Some slight confusion, courtesy of Microsoft (?) #include using namespace std; You are allowed to use this type 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:,,,,,,,, There are lots more: see “Library, Standard C++” in MSDN index You can include C headers (and use C functions) in C++ programs =

17 C++ The ‘string’ class o The standard string class is very useful; saves a lot of work o Many (library) functions require C strings (char*) o The string class can be used to manipulate and create C strings #include 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 string include finding sub-strings, getting string length, ==,, != and lots more… See “string” and “basic_string” in the MSDN documentation

18 C++ Worked example: ‘finite’ (I) Neighbour ‘this’ element 1)Create grid of elements dymanically 2)Initialise elements – random values 3)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 addresses of its neighbouring elements

19 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

20 C++ The End Fortran C++ The only way to learn a computer programming language is to program in it


Download ppt "C++ C++ Overview (I) What is Object Orientated Programming? Approach: Break problem into subgroups of related parts that take into account code and data;"

Similar presentations


Ads by Google