cs3340 – oop and c++

22
CS3340 – OOP and C++ CS3340 – OOP and C++ L. Grewe L. Grewe

Upload: flavia-miranda

Post on 30-Dec-2015

57 views

Category:

Documents


1 download

DESCRIPTION

CS3340 – OOP and C++. L. Grewe. C++ is an object-oriented programming language. Who created C++? Bjarne Stroustrup, while at AT&T. (now, a professor in Computer Science at Texas A&M University) http://www.research.att.com/~bs/. C++. Overview. C++ basics (see course website) - PowerPoint PPT Presentation

TRANSCRIPT

CS3340 – OOP and C++CS3340 – OOP and C++

L. GreweL. Grewe

C++C++

C++ is an object-oriented programming language.

Who created C++? Bjarne Stroustrup, while at AT&T. (now, a professor in Computer Science at Texas A&M University)

http://www.research.att.com/~bs/

OverviewOverview

C++ basics (see course website)C++ basics (see course website) C++ and OOP concepts revisitedC++ and OOP concepts revisited

Two ways of code reuse: composition & inheritance

Composition (“has-a” relationship): An object of a class has an object of another class in

it. Use predefined code of a class by creating an object of the class.

Inheritance (“is-a” relationship):A child class inherits everything from its parent

class. Use predefined code of a class by sub-classing from it.

class CWheel { private:

float air-pressure;public:

void inflate();…

}; // predefined class

class CPassengerCar { private:

int number-of-seats;CWheel fl-wheel, fr-wheel;CWheel rl-wheel, rr-wheel;

public:…

};

class CCar { private:

CEngine engine;CBreak break;

public:void accelerate();void stop();…

}; // predefined class

class CPassengerCar : public CCar { private:

int number-of-seats;CWheel fl-wheel, fr-wheel;CWheel rl-wheel, rr-wheel;

public:…

};

“a passenger car is a car” “a truck is a car” “a race car is a car”

class CCar { private:

CEngine engine;CBreak break;

public:void accelerate();void stop();…

};

Grouping data and operations (functions/methods) together to facilitate code reuse.

Controlling the access of the members. (Private members are hidden and can only be accessed by the member functions of the class. Users can only use the given public functions to alter the private data members).

class CCar { protected:

CEngine engine;CBreak break;

public:void accelerate();void stop();…

};

Protected members are hidden and can only be accessed by the member functions of the class and its decedent classes.

class CShape { private: int color;public: virtual float area() { };

// a virtual function can be overridden by the children };

One method behaves differently for different objects.

class CCircle : public CShape{ public:

float area() {return (pi * r * r)}; };

class CRect : public CShape{ public:

float area() {return (w*h)}; };

CShape *shapes[4];CCircle *c1 = new CCircle(5);CCircle *c2 = new CCircle(10);CRect *r1 = new CRect(4,5);CRect *r2 = new CRect(8,5);

shapes[0] = (CShape *) c1; // cast to parent allowedshapes[1] = (CShape *) c2; // cast to parent allowedshapes[2] = (CShape *) r1; // cast to parent allowedshapes[3] = (CShape *) r2; // cast to parent allowed

for (I=0; I<4; I++) cout << shapes[I]->area() << endl;

One function behaves differently for different objects.

Interface in C++ ……Use Interface in C++ ……Use Abstract ClassAbstract Class

There is no “Interface” in C++. The workaround is to define abstract classes with pure virtual functions. Pure virtual functions: have only function headers (APIs), but no function bodies.

virtual return-type function-name (argument list) = 0; Abstract classes: have one or more pure virtual functions; can be used for inheritance by child classes, can not be used for instantiation of objects. The child classes are required to implement all pure virtual functions with predefined APIs.

Polymorphism makes it possible for objects of different child classes to have the same interface.

To enforce a standard interface, one can make the parent class an abstract class and subclass from it.

An abstract class is a class containing a pure virtual function. One can’t instantiated an abstract class. It is just for setting up standard interfaces. Its child classes must override and implement the pure virtual function. (A regular virtual function is not required to be overridden by the child classes and it is inherited if it is not overridden.)

Setting up standard interfaces

class CShape { public:

virtual float area() = 0; // a pure virtual function

}; // CShape a-shape; not allowed.

class CCircle : public CShape{ public:

float area(); // must be implemented. };

class CRect : public CShape{ public:

float area(); // must be implemented. };

Common OOP need - Common OOP need - IteratorsIterators

•traverse a collection of objects from the beginning to the end. • iterators have been implemented for all C++ collection classes (e.g. vector).•Have templates (like generics in Java)

vector<Shape *> shapes;…vector<Shape *>::iterator it = shapes.begin();    while(it != shapes.end()) (*it++)->display();

Coding with an IDE (MS Visual Studio 2XXX)Coding with an IDE (MS Visual Studio 2XXX)

Using Start->Program Files-> MS Visual Studio 2XXX-> MS Visual Studio XXXX

Select C++ as default environment if prompted to.File->New->Project->

Other Languages->Visual C++->Win32->Win32 Console ApplicationName: testLocation: My Documents\Visual Studio 2XXX\Projects (fix this to a location…like your USB fob that you will remember to take with you)

The actual sequence will depend on your version ofMS Visual Studio

Some Review and other thingsSome Review and other things

I/O , file I/OI/O , file I/O TemplatesTemplates VectorVector Protection typesProtection types pointerspointers

Console IOConsole IO Reading Input: cin

console input an object of iostreams only supports one operator >> reads input for its arguments, one at a time auto converts input to the type of the arguments

Displaying Output: cout console output an object of iostreams only supports one operator << sends output to the console for its arguments, one at a time auto converts output of the type of the arguments for display display format can be specified

File IOFile IO#include <string>#include <fstream> // file io streams#include <iostream> // file io streamsusing namespace std;

int main() {string infile, outfile;

cout << "Enter input file name: \n";cin >> infile;cout << "Enter output file name: \n";cin >> outfile;

ifstream in(infile.data()); // Open for reading ofstream out(outfile.data()); // Open for writing string s; while(getline(in, s)) // Discards newline char out << s << "\n"; // ... must add it back}

Protection TypeProtection Typepublic, private and protectedpublic, private and protected

public members are accessible to all.public members are accessible to all. protected members are accessible toprotected members are accessible to

derived class. derived class. private accessible only to same private accessible only to same

class.class.

vector (smart array)vector (smart array)To use:

#include <vector>To define:

vector <type> v;To add an element:

v.push_back(object);To access an element:

v[i] (just like an array)Eaxmples:

vector<int> vi; vector<string> vs; int i; string s;cin >> i >> s;vi.push_back(i); vs.push_back(s); cout << vi[0] << vs[0];

Address of a VariablesAddress of a Variables&• Operator & returns the address of an variable

e.g.: &i, &ia[0], &ia[1]• The address of a memory is expressed as a hex number

e.g.: 0xffaabbcc

Pointers in C and C++Pointers in C and C++

int i = 8;ip = &i;

i

Pointer • A pointer is a named memory space. • The size of the memory is determined by the OS (32 bits, 64 bits,

…), and it determines the maximum addressing space of the OS.• The memory space of a pointer stores the address of another

memory space. We usually say, the pointer points to the memory space.

• The size of the pointed memory space is determined by the type of the pointer.

• A pointer is declared astype * name;

8

0xffaabbcc

Example: int * ip //ip (4 bytes of memory for a 32bit OS)