Object Oriented Programming COP3330 / CGS5409

Similar documents
Protection Levels and Constructors The 'const' Keyword

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Object Oriented Modeling

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 247: Software Engineering Principles. ADT Design

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Classes and Objects. CGS 3416 Spring 2018

Introduction Of Classes ( OOPS )

III. Classes (Chap. 3)

Lecture 7. Log into Linux New documents posted to course webpage

Data Structures using OOP C++ Lecture 3

Short Notes of CS201

Cpt S 122 Data Structures. Introduction to C++ Part II

CS201 - Introduction to Programming Glossary By

Object-Oriented Programming Concepts

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

ADTs & Classes. An introduction

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Fast Introduction to Object Oriented Programming and C++

An Introduction to C++

Abstract Data Types. Development and Implementation. Well-defined representations that allow objects to be created and used in an intuitive manner

CPSC 427a: Object-Oriented Programming

Implementing an ADT with a Class

Initializing and Finalizing Objects

Data Structures and Other Objects Using C++

Abstraction in Software Development

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Determine a word is a palindrome? bool ispalindrome(string word, int front, int back) { Search if a number is in an array

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

10.1 Class Definition. User-Defined Classes. Counter.h. User Defined Types. Counter.h. Counter.h. int, float, char are built into C+ Declare and use

SFU CMPT Topic: Classes

Inheritance, and Polymorphism.

Fundamental Concepts and Definitions

Object Oriented Programming in C#

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value


Fundamentals of Programming. Lecture 19 Hamed Rasifard

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 4 Defining Classes I

Object-Oriented Principles and Practice / C++

System Design and Programming II

Defining Classes and Methods

Friends and Overloaded Operators

Module 7 b. -Namespaces -Exceptions handling

Friends and Overloaded Operators

Object-Oriented Programming

Chapter 6 Introduction to Defining Classes

Circle all of the following which would make sense as the function prototype.

EL2310 Scientific Programming

Object Oriented Programming COP3330 / CGS5409

Constructor - example

Lecture 13: more class, C++ memory management

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Ch 8. Operator Overloading, Friends, and References

Lecture #1. Introduction to Classes and Objects

Interview Questions of C++

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Recharge (int, int, int); //constructor declared void disply();

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Polymorphism Part 1 1

Classes. C++ Object Oriented Programming Pei-yih Ting NTOU CS

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

7.1 Optional Parameters

Object-Oriented Programming, Iouliia Skliarova

Encapsulation in C++

Class 15. Object-Oriented Development from Structs to Classes. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

A <Basic> C++ Course

CS 162, Lecture 25: Exam II Review. 30 May 2018

A <Basic> C++ Course

Module Operator Overloading and Type Conversion. Table of Contents

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

C++ Classes, Constructor & Object Oriented Programming

Object Oriented Programming(OOP).

What will this print?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Comments are almost like C++

PIC 10A. Lecture 17: Classes III, overloading

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

More class design with C++ Starting Savitch Chap. 11

Function Overloading

PIC 10A. Lecture 15: User Defined Classes

Object Reference and Memory Allocation. Questions:

Chapter 15: Object Oriented Programming

Structures. Lecture 15 COP 3014 Spring April 16, 2018

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Object Oriented Programming

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Transcription:

Object Oriented Programming COP3330 / CGS5409

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

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

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

General outline for OOP: Declare Define Use

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.

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.

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.

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

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.

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

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 <classname> { public: (public member data and functions go here) private: (private member data and functions go here) };

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

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

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

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

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.

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

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 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!

// circle.h class Circle { public: bool setradius(int r); bool setradius2(int radius); int getradius(); private: int radius; }

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

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

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

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

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!

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?

Problem: Multiple internal calls to functions GetNumerator() and GetDenominator() Not the most efficient 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!

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

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

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

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

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

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

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

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

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)

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

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

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; y.func(5); // object y // function will not change data of y

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

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

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

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;

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 }

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

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 initialization example Thing::Thing() : LIMIT(10) // initialization //of const member { height = 0; weight = 0; cout << SIZE; }

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

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

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.