data structures - csci 102 cs102 c++ object-oriented...

36
1 Data Structures - CSCI 102 Copyright © William C. Cheng CS102 C++ Object-Oriented Programming Bill Cheng http://merlot.usc.edu/cs102-s12

Upload: dodang

Post on 13-Mar-2018

255 views

Category:

Documents


1 download

TRANSCRIPT

1

Data Structures - CSCI 102

Copyright © William C. Cheng

CS102C++ Object-Oriented

Programming

Bill Cheng

http://merlot.usc.edu/cs102-s12

Polymorphism (Ch 13)Virtual functionsAbstract classesInterfaces

Pointers & Dynamic Objects (Ch 13)

C Structs (Ch 10)Topics to cover

2

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Object-Oriented Programming

C++ Classes (Ch 11)ConstructorsDestructorsMember functions

Exceptions (Ch 15)Namespaces (Ch 8)Operator Overloading (Ch 14)Class Composition & Inheritance (Ch 12)

C++ is an Object-Oriented Programming Language

Procedural Programming LanguageThis is the traditional programming language

Other major programming paradigms:

You write proceduresYou use a lot of variables all over the placeFortran, C, Pascal, etc.

Functional Programming LanguageIn its pure form, a function call must not have any side effects (such as changing a global variable or produce any output)In Lisp, function and data are the same type of objects

You can pass a function around like dataYou can construct a piece of data and invokeit like a function 3

Data Structures - CSCI 102

Copyright © William C. Cheng

Major Programming Paradigms

Polymorphism to extend existing implementation

Declarative Programming LanguageMake declarative statements

Other major programming paradigms:

Object-Oriented Programming LanguageViews the world as a collection of objects

Objects has internal data/states and external means of accessing/manipulating the data/states

Reusability through inheritance

Let the interpreter figure out what statement to execute nextLogic Programming, e.g., Prolog

Java, C++

C++ is an Object-Oriented Programming Language

4

Data Structures - CSCI 102

Copyright © William C. Cheng

Major Programming Paradigms

Needed a way to group components that are related, but have different data types

5

Data Structures - CSCI 102

Copyright © William C. Cheng

C Structs

Members are public by default

NOTE: struct has changed in C++!

struct Person{ char name[20]; int age;};

Difficult to make sure that no one will set age to a negative value!

if this object class is to be used by others

It is probably the most widely known and used notation for object-oriented analysis and design

Unified Modeling Language (UML) is the set of notations, models and diagrams used when developing object-oriented (OO) systems

6

Data Structures - CSCI 102

Copyright © William C. Cheng

Object-Oriented Design

UML helps you specify, visualize, and document models of software systems, including their structure and design

You will probably learn UML in your Software Engineering classes

We will borrow some UML notations

In object-oriented design, an object has attributes and operations

7

Data Structures - CSCI 102

Copyright © William C. Cheng

Objects

Attributes are also known as propertiesAttributes can be other objectsFor example, attributes for a car can be its make, model, model year, VIN number, paint color, etc.

can also be things in this car such as engine,breaks, stereo equipment, GPS, wheels, ski rack, bike rack, etc.

Attributes:

The object type is called its classA class definition specifies what attributes an object instance of this class must have and the operations implemented for this classCreating an instance of an object is called instantiation

8

Data Structures - CSCI 102

Copyright © William C. Cheng

Objects

Operations are things that you can do to affect the object(or attribute values of the object)

Operations:

For example, operations for a car can be OilChange(), TransmissionRebuild(), RotateTires(), UpgradeStereo(), PutOnSnowChains(), ApplyPaintJob(), etc.

9

Data Structures - CSCI 102

Copyright © William C. Cheng

Driver/Client program

A program/application that uses the classDriver/Client program:

Create an instance of a primary object by instantiatingan instance of the main object class

Interact with the user to get user inputnot limited to one

instantiate object instances of other classes as neededfree up object instance when they are no longer needed

Typically speaking:

10

Data Structures - CSCI 102

Copyright © William C. Cheng

UML RepresentationClass

ClassName

Attributes

Operations

Visibility: use visibility markers tosignify who can access the information contained within a class.

Private visibility hides informationfrom anything outside the classpartition.

ClassNameAttributesOperations

Public visibility allows all other classesto view the marked information.Protected visibility allows child classes to access information they inherited from a parent class.

+-#

publicprivateprotected

11

Data Structures - CSCI 102

Copyright © William C. Cheng

Example - UML RepresentationEx: design a class to represent rectangles

Analysis:Attributes

width (float)height (float)area (float)perimeter (float)

OperationsProvide accessors (getters) for all attributesProvide modifiers (setters) for width and lengthProvide calculation for area and perimeter

getWidth(): floatgetHeight(): floatgetArea(): floatgetPerimeter(): floatsetWidth(float): voidsetHeight(float): voidCalcArea(): voidCalcPerimeter(): voidRectangle()Rectangle(float,float) 12

Data Structures - CSCI 102

Copyright © William C. Cheng

Example - UML RepresentationEx: design a class to represent rectangles

Rectangle

----

width: floatheight: floatarea: floatperimeter: float

++++++++

An expanded data structureCan contain related data AND functions

What are C++ classes?

13

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes

A composition mechanismCreate really large and powerful software systems from tiny componentsSplit things up into manageable piecesDelegation of responsibility

An abstraction mechanismMake functionality publicly available, but hide data & implementation details

C++

Combine data and the functions that operate on that data into a single unit

Encapsulation

14

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Class Concepts

Hide all important data behind a well-controlled access interface

Data/Information Hiding

Separate the logic properties of an object from its implement details

Data Abstraction

Depend only on an interface! (e.g. a microwave)

Protect yourself from users & protect your users from themselves

Member variablesWhat data must be stored?

What are the main parts of a class?

15

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Overview

Constructor(s)How do you build an instance?

Member functionsHow does the user need to interact with the stored data?

DestructorHow do you clean up an after an instance?

Most common C++ operators will not work by default (e.g. ==, +, <<, >>, etc.)

Defaults is private (only class functions can access)Member data can be public or private (for now)

16

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Overview

Must explicitly declare something public

The only ones you get are ’=’ and ’.’

Pass them to functions (by copy, reference or pointer)Classes may be used just like any other data type (e.g. int)

Return them from functions

C++ won’t automatically initialize member variablesCalled when a class is instantiated

17

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Constructors

No return value

Default constructorTwo types

Overloaded constructors

Over time, the object changes state, from one consistent state to another

The goal of the constructors is to initialize the instance of your object into a consistent state

So, it better starts with a consistent state

The state of an object is just the collection of all the object’s member variables

This is also why member variables are private!

18

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Constructors

Can have one or none in a classDefault Constructor

Basic no-argument constructor

Can have zero or moreOverloaded Constructors

These constructors take in arguments

Has the name ClassName()If class has no constructors, C++ will make a default

If a class has overloaded constructor(s) but nodefault constructor, C++ will not make a defaultconstructor

Have access to all member variables of class

19

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Member Functions

void foo() { } vs. void ClassName::foo() { }Use the "scope resolution operator: :: to define

Use "const" keyword if it won’t change member datavoid ClassName::bar() const { }

Normal member accessClassName x; x.foo();

Pointer member accessClassName *y = &x;(*y).foo();y->bar();

Can have one or none

Called when a class goes out of scope or is freed from the heap (by " delete")

20

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Destructors

Destructor

If class has no destructor, C++ will make oneNo return valueHas the name ~ClassName()

Not necessary in simple casesWhy use it?

Clean up resources that won’t go away automatically (e.g. stuff you used " new" to create)

Works slightly different for an array of objects (see next slide)

When an array of n objects is deleted

21

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Destructors

Destructors of each of the n objects is calledThen the memory associated with the array is freed

Car car_array[...];

for (int i = 0; i < foo_array.size(); i++) { foo_array[i].~Car();}delete car_array;

Must use delete[]

ClassName.h - Contains interface descriptionClasses are generally split across two files

22

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Other Notes

ClassName.cpp - Contains implementation details

Make sure you remember to prevent circular dependencies in your header file with #ifndef

#ifndef CLASSNAME_H_#define CLASSNAME_H_

class ClassName { ... };

#endif

23

Data Structures - CSCI 102

Copyright © William C. Cheng

C++ Classes: Exampleclass Clock { private: int hours; int minutes; int seconds;

public: Clock(int h, int m, int s) { hours = h; minutes = m; seconds = s; }

void print() const { cout << hours << ":" << minutes << ":" << seconds; }};

Normally you declare your class variables and then initialize them separately

Space is allocated for variables

Normal Constructors

24

Data Structures - CSCI 102

Copyright © William C. Cheng

Constructor Initialization Lists

Members are assigned a value AFTER space has been allocated for them (via a constructor)

class Point { private: int x; int y;

public: Point() { x=0; y=0; }};

Space is allocated for variables

Alternately you can declare your class variables and then initialize immediately

25

Data Structures - CSCI 102

Copyright © William C. Cheng

Constructor Initialization Lists

Members are assigned a value AT THE SAME TIME as space has been allocated for them

class Point { private: int x; int y; public: Point() : x(0), y(0) { }

Point(int newx, int newy) : x(newx), y(newy)) { }};

class Creature { private: string name; int hitPoint; Point location; public: Creature(string n, int hp, int x, int y) : name(n), hitPoint(hp), location(x,y)) { }};

Initializing variables in the body of a class constructor is akin to doing this:

26

Data Structures - CSCI 102

Copyright © William C. Cheng

Constructor Initialization Lists

int x;x = 5;

Initializing variables in a constructor initialization list is akin to doing this:

int x = 5;

Why should you care? What’s wrong with using the constructor body for initialization?

27

Data Structures - CSCI 102

Copyright © William C. Cheng

Constructor Initialization Lists

It won’t work in certain casesconst and reference variables must be assigned right when they’re declared

It makes object composition difficultWhat if your class contains other classes?How do you call another class’ constructor?

It’s the only way to call base class constructors when you’re doing inheritance

The normal way is fine, but sometimes you MUST do things this way

int hours, int minutes, int secondsWhat members does it need?

28

Data Structures - CSCI 102

Copyright © William C. Cheng

Class Example: Basic Clock

get/set timeWhat operations might it have?

Let’s write some code...

Print the timeIncrement hours, minutes or secondsCompare two times for equality

int getHours() const { ... }

int setHours(...)

bool equals(...) const

bool operator==(...) const

cout << boolalpha << c2.equal(c) << endl;

29

Data Structures - CSCI 102

Copyright © William C. Cheng

CS102Extra Slides

Bill Cheng

http://merlot.usc.edu/cs102-s12

30

Data Structures - CSCI 102

Copyright © William C. Cheng

clock.h/* * 1) A class to represent a basic clock that can track hours, * minutes and seconds. See your book for a complete * example. * 2) hours, minutes, seconds should be private. * 3) Default constructor. Init all members to 0. * 4) Overloaded constructor. Set values to h,m,s. * 5) Need accessor for hours, minutes, and seconds called * getHours(), getMinutes(), and getSeconds(). * 6) Need mutator for hours, minutes, and seconds called * setHours(), setMinutes(), and setSeconds(). * 7) Need a print() function to print out the clock to the * console (with newline). * 8) Write a equal() function to compare this clock and * another clock for equality. */

31

Data Structures - CSCI 102

Copyright © William C. Cheng

clock.h#ifndef CLOCK_H_#define CLOCK_H_

class Clock{ private: int hours; int minutes; int seconds; public: Clock(); Clock(int hours, int m, int s); int getHours() const; void setHours(int h); int getMinutes() const; void setMinutes(int m); int getSeconds() const; void setSeconds(int s); void print() const; bool equals(const Clock& other) const;};

#endif

32

Data Structures - CSCI 102

Copyright © William C. Cheng

clock.cpp/* * 1) Get use to the habit of using this-> when accessing * a class member. This way, you don’t have to wonder * if something is a class member or not. * 2) If hour, minute, or second is out of range, don’t * change the value. * 3) In print(), use setfill(’0’) for leading zeroes and * use setw(2) to print two digits. This is the * normal way a clock is displayed. */

33

Data Structures - CSCI 102

Copyright © William C. Cheng

clock.cpp#include <iostream>#include <iomanip>

#include "clock.h"

using namespace std;

#define WIDTH 2

Clock::Clock(){ this->hours = 0; this->minutes = 0; this->seconds = 0;}

Clock::Clock(int hours, int m, int s){ this->hours = hours; minutes = m; seconds = s;}

int Clock::getHours() const{ return this->hours;}

void Clock::setHours(int h){ if(h >= 0 && h <= 23) { this->hours = h; }}

int Clock::getMinutes() const{ return this->minutes;}

void Clock::setMinutes(int m){ if(m >= 0 && m <= 59) { this->minutes = m; }}

int Clock::getSeconds() const{ return this->seconds;}

void Clock::setSeconds(int s){ if(s >= 0 && s <= 59) { this->seconds = s; }} void Clock::print() const{ cout << setfill(’0’); cout << setw(WIDTH) << hours << ":" << setw(WIDTH) << minutes << ":" << setw(WIDTH) << seconds << endl;}

bool Clock::equals(const Clock& other) const{ return hours == other.hours && this->minutes == other.minutes && this->seconds == other.seconds;}

34

Data Structures - CSCI 102

Copyright © William C. Cheng

clock.cpp (Cont...)

/* * 1) Demonstrate rudimentary use of the Clock class. * 2) c1 is a clock, print it. * 3) c2 is a clock, print it. * 4) Print to see if c1 equals c2 (need to use the boolalpha * manipulator. * 5) Change the hour, print the clock. * 6) Create a clock in the heap, point to it, change its * hour using both (*ptr). and ptr-> syntax. */

35

Data Structures - CSCI 102

Copyright © William C. Cheng

clock_main.cpp

#include <iostream>#include <iomanip>

#include "clock.h"

using namespace std;

int main(){ Clock c1(0,0,1); c1.print();

Clock c2(10,55,20); c2.print(); cout << boolalpha << c2.equals(c1) << endl;

Clock c; c.setHours(10); cout << c.getHours() << endl; //c.hours = 10; "hours" is private...can’t do this! Clock* cptr = &c; (*cptr).setMinutes(55); //cptr->setMinutes(55); //alternate syntax}

36

Data Structures - CSCI 102

Copyright © William C. Cheng

clock_main.cpp