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

Slides:



Advertisements
Similar presentations
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
1 Objects and ClassesStefan Kluth 1.6Objects and Classes 1.6What is an Object? 1.7Objects and Classes 1.8Object Interface, Class Inheritance, Polymorphism.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
C++ fundamentals.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
C++ Yeting Ge.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
Object Oriented Programming using C++. Overview Problem Solving Features of an OOL Basic Syntax Programming Paradigms.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Object-Oriented Programming in C++
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 24P. 1Winter Quarter C++ Lecture 24.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Object-Oriented Programming in C++ More examples of Association.
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
Structures, Classes and Objects Handling data and objects Unit - 03.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
ENEE150 – 0102 ANDREW GOFFIN Abstract Data Types.
Starting Out with C++, 3 rd Edition 1 Chapter 13 – Introduction to Classes Procedural and Object-Oriented Programming Procedural programming is a method.
1 n Object Oriented Programming. 2 Introduction n procedure-oriented programming consists of writing a list of instructions and organizing these instructions.
Learners Support Publications Constructors and Destructors.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Constructors and Destructors
CS3340 – OOP and C++ L. Grewe.
Introduction to Classes
Chapter 5 Classes.
Introduction to Classes
CS212: Object Oriented Analysis and Design
Constructors and Destructors
CS410 – Software Engineering Lecture #5: C++ Basics III
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Lecture 8 Object Oriented Programming (OOP)
Presentation transcript:

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!

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)

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

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

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

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

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

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

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

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

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

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

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

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

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

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 =

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

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

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