Download presentation
Presentation is loading. Please wait.
Published byΝάρκισσα Κουντουριώτης Modified over 6 years ago
1
Object Oriented Programming COP3330 / CGS5409
Recitation Week 3 Object Oriented Programming COP3330 / CGS5409
2
Today’s Recitation Classes & Objects DDU Design Constructors
Member Functions & Data Friends and member functions Const modifier Destructors
3
Object 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)
4
Class 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.
5
Classes & Objects An object is a single instance of a class.
Many objects can be created from the same class type.
6
DDU Design General outline for OOP: Declare Define Use
7
DDU Design - Declare 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.
8
DDU Design - Define 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.
9
DDU Design - Use 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.
10
OOP & Interfaces 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).
11
Class protection levels
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.
12
Class protection levels
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
13
Class protection levels
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.
14
Class Declaration Format
class <className> { public: (public member data and functions go here) private: (private member data and functions go here) };
15
Class Declaration Example
// 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; };
16
Class Declaration Example
// declaration for class of TimeType objects class 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; };
17
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
18
Constructors Example // declaration of a class of Circle objects class Circle { public: Circle(); // this is a CONSTRUCTOR Circle(double r); // also a CONSTRUCTOR void SetCenter(double x, double y); void SetRadius(double r); void Draw(); double AreaOf(); private: double radius; double center_x; double center_y; };
19
Constructors, cont. 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.
20
Constructors with Parameters
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
21
Constructors with Parameters cont
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
22
Member Functions & Data
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!
23
Member Functions & Data Example
// circle.h class Circle { public: bool setRadius(int r); bool setRadius2(int radius); int getRadius(); private: int radius; }
24
Member Functions & Data Example
// circle.h class Circle { public: bool setRadius(int r); // parameter required since user supplied value must be input bool setRadius2(int radius); int getRadius(); private: int radius; }
25
Member Functions & Data Example
// circle.h class 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; }
26
Member Functions & Data Example
// circle.h class Circle { public: bool setRadius(int r); bool setRadius2(int radius); int getRadius(); // No parameters necessary! Function has full access to private variable radius private: int radius; }
27
Comparison Function s 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";
28
Comparison Function s 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!
29
Sample Implementation
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?
30
Sample Implementation
Problem: Multiple internal calls to functions GetNumerator() and GetDenominator() Not the most efficient implementation!
31
Another Implementation
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!
32
Alternative: the keyword friend
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
33
Frac.h – with friends 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; };
34
Frac.cpp – with friends … #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); } …
35
Another Alternative: member functions
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";
36
Another Alternative: member functions
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; }
37
Side by Side Comparison
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);
38
Type-Conversions 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
39
Conversion 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
40
Explicit use of 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
41
Using const in classes 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)
42
Revisiting const reference parameters
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
43
pass-by-value example
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).
44
const Member Functions
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 y y.Func(5); // function will not change data of y
45
const Member Functions
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
46
Declaring const objects
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 = ;
47
Declaring const objects
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
48
Calling const objects 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();
49
const Member Data 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;
50
const Member Data 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 }
51
const Member Data 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; }
52
const Member Data 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 }
53
const Member Data Const member initialization example
Thing::Thing() : LIMIT(10) // initialization //of const member { height = 0; weight = 0; cout << SIZE; }
54
Destructors 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();
55
Destructors 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).
56
Destructors 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.
57
Questions?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.