Object Oriented Programming COP3330 / CGS5409

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
IT PUTS THE ++ IN C++ Object Oriented Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Matthew Small Introduction to Object-Oriented Programming.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Object Oriented Programming COP3330 / CGS5409.  Classes & Objects  DDU Design  Constructors  Member Functions & Data  Friends and member functions.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Procedural and Object-Oriented Programming
Classes (Part 1) Lecture 3
Chapter 7: User-Defined Functions II
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Abstract Data Types Programmer-created data types that specify
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
7. Inheritance and Polymorphism
Review What is an object? What is a class?
Programming with ANSI C ++
Andy Wang Object Oriented Programming in C++ COP 3330
Java Primer 1: Types, Classes and Operators
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Object Oriented Programming COP3330 / CGS5409
A First C++ Class – a Circle
Andy Wang Object Oriented Programming in C++ COP 3330
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Introduction to Classes
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
More on Classes Programming in C++ Fall 2008
Andy Wang Object Oriented Programming in C++ COP 3330
Introduction to Classes
Defining Classes and Methods
CS212: Object Oriented Analysis and Design
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 9 Objects and Classes
Learning Objectives Classes Constructors Principles of OOP
Constructors and Other Tools
Classes and Objects.
Defining Classes and Methods
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
Andy Wang Object Oriented Programming in C++ COP 3330
COP 3330 Object-oriented Programming in C++
Chapter 9 Introduction To Classes
Lecture 8 Object Oriented Programming (OOP)
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Classes and Objects Systems Programming.
Presentation transcript:

Object Oriented Programming COP3330 / CGS5409 Recitation Week 3 Object Oriented Programming COP3330 / CGS5409

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

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)

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.

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

DDU Design General outline for OOP: Declare Define Use

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.

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.

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.

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

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.

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

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.

Class Declaration Format class <className> { public: (public member data and functions go here) private: (private member data and functions go here) };

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

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

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

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

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.

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

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

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!

Member Functions & Data Example // circle.h class Circle { public: bool setRadius(int r); bool setRadius2(int radius); int getRadius(); private: int radius; }

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

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

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

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

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!

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?

Sample Implementation Problem: Multiple internal calls to functions GetNumerator() and GetDenominator() Not the most efficient implementation!

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!

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

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

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

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

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

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

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

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

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

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)

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

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

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

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

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 = 3.1415;

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

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

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;

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 }

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

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 }

const Member Data Const member initialization example Thing::Thing() : LIMIT(10) // initialization //of const member { height = 0; weight = 0; cout << SIZE; }

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

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

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.

Questions?