object oriented programming cop3330 / cgs5409. classes & objects ddu design constructors…

57
Object Oriented Programming COP3330 / CGS5409

Upload: norman-miller

Post on 20-Jan-2018

240 views

Category:

Documents


0 download

DESCRIPTION

 Object -- an encapsulation of data along with functions that act upon that data.  An object consists of: ◦ Name -- the variable name we give it ◦ Member data -- the data that describes the object ◦ Member functions -- behavior aspects of the object (functions related to the object itself)

TRANSCRIPT

Page 1: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Object Oriented ProgrammingCOP3330 / CGS5409

Page 2: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors

Page 3: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Object -- an encapsulation of data along with functions that act upon that data.

An object consists of:◦ Name -- the variable name we give it ◦ Member data -- the data that describes the object ◦ Member functions -- behavior aspects of the

object (functions related to the object itself)

Page 4: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Class -- a blueprint for objects. They are user-defined types that describes what a certain type of object will look like.

Class description consists of:◦ Declaration◦ Definition.

Usually these pieces are split into separate files.

Page 5: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

An object is a single instance of a class. Many objects can be created from the same

class type.

Page 6: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

General outline for OOP:◦Declare◦Define◦Use

Page 7: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Declare - A declaration gives an interface:◦A variable declaration gives the type. ◦A function declaration tells how to use it,

without bothering with how it works. ◦A class declaration shows what an object

will look like and what its available functions are.

Page 8: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Define - A definition usually consists of the implementation details.  ◦A function definition is the code that

makes a function work (the function body). 

◦A class definition consists definitions of its members.

Page 9: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Use - The use of an item, through its interface. ◦ The user of an executable program uses the

graphic interface, keyboard, and mouse. ◦ The user of a function is a programmer, who

makes calls to the function (without needing to know the implementation details). 

◦ The user of a class is also a programmer, who uses the class by creating objects and calling the available functions for those objects.

Page 10: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

The concept of interface is a very important one in object-oriented programming.

The interface is what the user sees.  (often leave the implementation details hidden)

Goal: clear interface for the user (not necessarily the end user of a program -- could be a programmer, i.e. the user of a class).

Page 11: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

We can declare members of a class to be public or private.◦ public - can be accessed from inside or outside of

the object. ◦ private - can only be used by the object itself.

Page 12: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

What should be public? Kept private? No set rules on what belongs where Standard practices:

◦ Protect member data of a class by making it private

◦ Functions internal to program (will not ever be called by a class user) should also be private

Page 13: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Reasons for data hiding: ◦ Makes interface simpler for user. ◦ Principle of least privilege (need-to-know) ◦ More secure.  Less chance for misuse (accidental

or malicious). ◦ Class implementation easy to change without

affecting other modules that use it.

Page 14: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

class <className> { public:

(public member data and functions go here)

private: (private member data and functions go here)

};

Page 15: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// declaration of a class of Circle objects class Circle { public:

void SetCenter(double x, double y); void SetRadius(double r); void Draw(); double AreaOf();

private: double radius; double center_x; double center_y;

};

Page 16: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// declaration for class of TimeType objectsclass TimeType { public:

void Set(int, int, int); // set the time void Increment(); // increment the timer void Display(); // output the time // accessor functions int GetHours(); int GetMinutes(); int GetSeconds();

private: int hours; int minutes; int seconds;

};

Page 17: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

A constructor is a special member function of a class whose purpose is usually to initialize the members of an object.

A constructor is easy to recognize: ◦ It has the same name as the class ◦ It has no return type

Page 18: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// declaration of a class of Circle objects class Circle { public:

Circle(); // this is a CONSTRUCTORCircle(double r); // also a CONSTRUCTORvoid SetCenter(double x, double y); void SetRadius(double r); void Draw(); double AreaOf();

private: double radius; double center_x; double center_y;

};

Page 19: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

A constructor is a function, and you can define it to do anything you want. 

However, you do not explicitly call the constructor function.  It is automatically called when you declare an object.  Example:   Look at the following declaration.

Circles circ1; This declaration creates an object named

circ1.  This line of code also causes the Circles constructor function to be run for the circ1 object.

Page 20: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

This fraction example contains the two following constructors:

Fraction(); // default constructor Fraction(int n, int d = 1); // constructor with parameters

The term default constructor will always refer to a constructor with no parameters.

When we declared objects in the simple fraction example, its default constructor was used because no parameters were passed.

Fraction f1, f2; // f1 and f2 are now Fraction objects

Page 21: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

To utilize a constructor with parameters, we can pass arguments in when the object is declared. Examples:

Fraction f1(2,3); // passes 2 and 3 as parameters int x = 4, y = 8; Fraction f2(x,y); // passes values stored in x and y Notice, also, that this constructor has a default

value on the second parameter, which makes it an optional parameter.  If only one argument is passed in, the second parameter takes the default value, 1.

Fraction f3(6); // initializes a fraction to 6/1

Page 22: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Member functions have CLASS scope Member functions have full access to all

public AND private data & functions. PRIVATE DATA DOES NOT NEED TO BE

PASSED TO FUNCTION!

Page 23: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// circle.hclass Circle{public:      bool setRadius(int r);  bool setRadius2(int radius);       int getRadius();private:      int radius;}

Page 24: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// circle.hclass Circle{public:      bool setRadius(int r);  // parameter required since user supplied value must be input bool setRadius2(int radius);       int getRadius();private:      int radius;}

Page 25: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// circle.hclass Circle{public:      bool setRadius(int r);  bool setRadius2(int radius); // radius is a local variable for setRadius2() and NOT the class member variable radius!!! Declaration of such a parameter over shadows the private radius, so we have to use this->radius to access the class radius now      int getRadius();private:      int radius;}

Page 26: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

// circle.hclass Circle{public:      bool setRadius(int r);  bool setRadius2(int radius);       int getRadius();// No parameters necessary! Function has full access to private variable radiusprivate:      int radius;}

Page 27: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Suppose we want to compare two Fraction objects:

Fraction f1(1,2); Fraction f2(2,4);

if ( Equals(f1, f2) ) // compare two objects cout << "The fractions are equal";

Page 28: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Equivalently, we can define the prototype:

bool Equals(Fraction x, Fraction y);

Important notes: Function takes TWO Fraction objects as

parameters Therefore, CANNOT be a member function!

Page 29: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

bool Equals(Fraction x, Fraction y) { if (x.GetNumerator() * y.GetDenominator() == y.GetNumerator() * x.GetDenominator() ) return true; else return false; }

What’s wrong with this implementation?

Page 30: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Problem: Multiple internal calls to functions GetNumerator() and GetDenominator()

Not the most efficient implementation!

Page 31: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

bool Equals(Fraction x, Fraction y) {

if (x.numerator * y.denominator == y.numerator * x.denominator )

return true; else

return false; }

No access to other objects' private data… NOT A LEGAL CALL!

Page 32: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Grant full access to an outside entity All member functions and variables, even

those declared as private To grant friend status, declaration of the

"friend" is made inside the class definition block, with the keyword friend in front of it

Page 33: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

class Fraction {

friend bool Equals(Fraction x, Fraction y); friend Fraction Add(Fraction x, Fraction y);

public: Fraction(); Fraction(int n, int d=1); void Input(); void Show(); int GetNumerator(); int GetDenominator(); bool SetValue(int n, int d); double Evaluate();

private: int numerator; int denominator;

};

Page 34: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

#include <iostream> #include "frac.h"

using namespace std; // friend functions bool Equals(Fraction x, Fraction y) {

return (x.numerator * y.denominator == y.numerator * x.denominator); } Fraction Add(Fraction x, Fraction y) {

int num = x.numerator*y.denominator + y.numerator*x.denominator; int denom = x.denominator * y.denominator; Fraction answer(num, denom); return answer; }

// member functions Fraction::Fraction() { numerator = 0; denominator = 1; } Fraction::Fraction(int n, int d) { if (SetValue(n,d) == false) SetValue(0,1); }

Page 35: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Another option is to use a member One of the objects must be the calling

object Example: The Equals() function could have

been set up as a member function, which would mean this kind of call:

if ( f1.Equals(f2) ) cout << "The fractions are equal";

Page 36: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

This is a member function for the calling object. The other object is passed as a parameter. This

would be the corresponding definition:

bool Fraction::Equals(Fraction f) {

if (numerator * f.denominator == f.numerator * denominator ) return true;

else return false;

}

Page 37: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Different programmers may have different preferences. Here's a comparison of the calls, side-by-side:

f3 = f1.Add(f2); // call to member version f3 = Add(f1, f2); // call non-member version

Also note that the member function version is not necessarily equivalent to the friend function:

Fraction Add(Fraction f); friend Fraction Add(Fraction f1, Fraction f2);

Page 38: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Recall how some of the built-in types allow automatic type conversions, like this:

int x = 5; double y = 4.5, z = 1.2;

y = x; // legal, via automatic conversion z = x + y; // legal, using automatic

// conversion

Page 39: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Automatic type conversions can also be set up for classes, via a conversion constructor

A conversion constructor is a constructor with one parameter ◦ By default, the compiler will use such a

constructor to enact automatic type conversions from the parameter type to the class type.

◦ Example: Fraction(int n); // can be used to convert int to

// Fraction

Page 40: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Constructors can be invoked explicitly to create Fraction objects.

Treat the constructor call as if it is returning an object of the constructed type. The conversion constructor will be invoked automatically when type conversion is needed:

Fraction f1, f2; // create fraction objects f1 = Fraction(4); // explicit call to constructor.

//Fraction 4 created and assigned to f1 f2 = 10; // implicit call to conversion constructor

// equivalent to: f2 = Fraction(10); f1 = Add(f2, 5); // uses conversion constructor

Page 41: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Const can be used in a variety of places. And everywhere it is applied in code, it: ◦ Expresses an intent on the part of the

programmer, which the compiler enforces (i.e. something is not allowed to change, within some scope)

◦ Expresses the intent more clearly to a user (in this case, another portion of code -- i.e. maybe another programmer)

Page 42: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Pass-by-value vs. Pass-by-reference works the same on objects as it does with built-in types.◦ If an object is passed by value, a copy is made of the

object. ◦ If an object is passed by reference (without const), no

copy is made Objects can be passed by const reference, as

well. This way, no copy is made (less overhead), but the object cannot be changed through the reference.

Since objects are sometimes large, this is often desirable

Page 43: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

This example used pass-by-value parameters:

friend Fraction Add(Fraction f1, Fraction f2); We definitely don't want to change the original

fractions that were sent in. But to save overhead, we could use const reference parameters:

friend Fraction Add(const Fraction& f1, const Fraction& f2);

Since the parameters are const, R-values can be sent in (just like with pass-by-value).

Page 44: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Another use of const is at the end of a member function prototype, like this:

void Func(int x) const; // const member function This application of const means that the function may not

change the calling object itself.◦ This can only be done to member functions of a class. (not stand-alone

functions).◦ This means that the member function will not change the member data

of that object.◦ If we have an object y, and then this function is called, the object y will

remain in the same state (before and after the function call):

Yadda y; // object yy.Func(5); // function will not change data of y

Page 45: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

When using this feature, the word const must go on the declaration and on the definition (if the definition is separate)

For good class design, it should be used whenever appropriate. This means on any member functions that should not alter the member data of the calling object: ◦ Constructors -- their job is to initialize the object (i.e. set the

member data), so these would NOT be const functions◦ Mutators -- usually Set functions. Their job is to change member

data, so these would also NOT be const◦ Accessors -- a pure accessor function's job is to retrieve data

from inside the class. These would typically be const member functions

Functions for printing -- Show() or Display() functions would be good candidates for const, if their only purpose was to print existing data

Page 46: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Declaring primitive type variables as const is easy.

Remember that they must be initialized on the same line:

const int SIZE = 10; const double PI = 3.1415;

Page 47: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Objects can also be declared as const. The constructor will always run to initialize the object, but after that, the object's state (i.e. internal data) cannot be changed

const Fraction ZERO; // this fraction is fixed const Fraction FIXED(3,4); // this fraction is // fixed at 3/4

To ensure that a const object cannot be changed, the compiler enforced the following rule:

A const object may only call const member functions

Page 48: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

So, using the Fraction class example with const member functions, the following calls are legal:

FIXED.Show(); // calling const functions cout << FIXED.Evaluate(); int n = ZERO.GetNumerator(); int d = ZERO.GetDenominator();

The following calls would be illegal and would cause compiler errors:

FIXED.SetValue(5,7); ZERO.Input();

Page 49: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Member data of a class can also be declared const.

This is a little tricky, because of certain syntax rules.

Remember, when a variable is declared with const in a normal block of code, it must be initialized on the same line:

const int SIZE = 10;

Page 50: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

However, it is NOT legal to initialize the member data variables on their declaration lines in a class definition block:

class Thing { public:

Thing(); // intialize member data here // functions

private: int x; // just declare here int y = 0; // this would be ILLEGAL! cannot // initialize here const int Z = 10; // would also be ILLEGAL

}

Page 51: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

But a const declaration cannot be split up into a regular code block. This attempt at a constructor definition would also NOT work, if Z were const:

Thing::Thing() {

x = 0; y = 0; Z = 10;

}

Page 52: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Solution: When we have lines like this, which involve declaring and initializing in one step and cannot be split up in normal code, we handle it with a special section of a function called the initialization list. Format:

returnType functionName(parameterList) : initialiation_list { // function body }

Page 53: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Const member initialization example

Thing::Thing() : LIMIT(10) // initialization //of const member

{ height = 0; weight = 0; cout << SIZE;

}

Page 54: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

In addition to the special Constructor function, classes also have a special function called a destructor.

The destructor looks like the default constructor (constructor with no parameters), but with a ~ in front. 

Destructors cannot have parameters, so there can only be one destructor for a class.  Example: 

~Fraction();

Page 55: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

Like the constructor, this function is called automatically (not explicitly)

A constructor is called automatically when an object is created.

A destructor is called automatically right before an object is deallocated by the system (usually when it goes out of scope).

Page 56: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…

The destructor's typical job is to do any clean-up tasks (usually involving memory allocation) that are needed, before an object is deallocated. 

However, like a constructor, a destructor is a function and can do other things, if desired.

Page 57: Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors…