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

Similar documents
Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Introduction Of Classes ( OOPS )

Object Oriented Programming. A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.

CS201 Some Important Definitions

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

CS

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

More C++ : Vectors, Classes, Inheritance, Templates

And Even More and More C++ Fundamentals of Computer Science

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

Object Oriented Programming(OOP).

Classes in C++98 and C++11

Initializing and Finalizing Objects

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Unit IV Contents. ECS-039 Object Oriented Systems & C++

Come and join us at WebLyceum

Programming, numerics and optimization

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Short Notes of CS201

Introduction to Classes

IS0020 Program Design and Software Tools Midterm, Fall, 2004

C++ (classes) Hwansoo Han

CS201 - Introduction to Programming Glossary By

C++ 8. Constructors and Destructors

Ch. 11: References & the Copy-Constructor. - continued -

Object oriented programming with C++

Intermediate Programming & Design (C++) Classes in C++

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

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

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

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

Abstraction in Software Development


Come and join us at WebLyceum

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Programming in C++: Assignment Week 4

Constructors for classes

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Chapter 1: Object-Oriented Programming Using C++

18. Polymorphism. Object Oriented Programming: Pointers to base class // pointers to base class #include <iostream> using namespace std;

6.096 Introduction to C++ January (IAP) 2009

Function Overloading


An Introduction to C++

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

OBJECT ORIENTED AND MULTICORE PROGRAMMING LABORATORY

Chapter 10 Introduction to Classes

C++ Constructor Insanity

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

EL2310 Scientific Programming

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

CSC1322 Object-Oriented Programming Concepts

CLASSES AND OBJECTS IN JAVA

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

Protection Levels and Constructors The 'const' Keyword

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

QUIZ. What is wrong with this code that uses default arguments?

The paramaterless ctor (aka default ctor)

Object-Oriented Principles and Practice / C++

Use the dot operator to access a member of a specific object.

Object Oriented Design

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Common Misunderstandings from Exam 1 Material

Object Oriented Programming COP3330 / CGS5409

QUIZ Friends class Y;

Name: Username: I. 10. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Programming in C++: Assignment Week 2

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Announcements. Lecture 04b Header Classes. Review (again) Comments on PA1 & PA2. Warning about Arrays. Arrays 9/15/17

Constructors & Destructors

G52CPP C++ Programming Lecture 13

Homework 4. Any questions?

CS32 - Week 1. Umut Oztok. June 24, Umut Oztok CS32 - Week 1

Instantiation of Template class

Polymorphism Part 1 1

Object-Oriented Principles and Practice / C++

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

Fast Introduction to Object Oriented Programming and C++

Praktikum: Entwicklung interaktiver eingebetteter Systeme

Object Oriented Software Design II

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

Object-Oriented Principles and Practice / C++

Chapter 11. Abstract Data Types and Encapsulation Concepts

COMP6771 Advanced C++ Programming

Lecture 18 Tao Wang 1

Software Design and Analysis for Engineers

For Teacher's Use Only Q No Total Q No Q No

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

CS201- Introduction to Programming Current Quizzes

OOP THROUGH C++(R16) int *x; float *f; char *c;

Constants, References

Introduction to C++ Systems Programming

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

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

Transcription:

Next week s homework Classes: Methods, Constructors, Destructors and Assignment Read Chapter 7 Your next quiz will be on Chapter 7 of the textbook For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar // classes example Classes: Member functions Member functions class Square int area () return (x*x);; ; // Typically in a.cpp file void Square::set_values(int a)x = a; int Square::get_sidelen(void) const return x; int main () Square s; s.set_values(3); std::cout << "area: " << s.area(); // Output: area: 9 Member functions: Methods Private members of a class are accessible only from within other members of the same class or from their friends. Protected members are accessible from members of their same class and from their friends, but also from members of their derived classes. Finally, public members are accessible from anywhere where the object is visible. Objects : Reminder Objects : Reminder An object is an instance of a class. Memory is allocated for each object instantiated (and not for the class). Example: Square S; // S is an object of Square class. (on stack) Square *ps = new Square; // on heap. An object of a class can be defined in the same way as an internal type. Multiple objects of a class can be created (as many as you want). All the objects share the same copy of member functions. But, they maintain a separate copy of data members. Square s1,s2; // each has separate copy of x 1

Objects: Reminder Assignment operator The data members and member functions of an object have the same properties as the data members and member functions of its class. Square s3 = s2; By default, copying a class object is equivalent to copying all its elements including pointers. Further study: https://www.programiz.com/cpp-programming/object-class Variable assignment Values are assigned to variables and not to their data types. Hence, you assign values to members of an object and not a class. Must create a unique object of a class because you cannot assign values to a class. Square = 5 is meaningless Back to member functions The member functions in the public section of a class can be accessed using the. operator for instantiated objects. (For pointers its -> ) Square s1, *s2; s1.set_values(5); s2 = new Square; s2->set_values(10); delete s2; Only the public members of an object can be directly accessed. Special Member functions Constructors vs. Destructors Constructors: Are invoked to initialize the data members of a class. Can not return any value (not even void). Can accept any parameters as needed. What would happen if we called the member function area() before having called function set_values()? Constructors initialize the objects in your class. Destructors clean up and free memory you may have allocated when the object was created. 2

Constructors Constructors Differs from other member functions. Initializes a newly created object. Other member functions are invoked by existing objects. A Constructor is invoked automatically when an object is created. Have the same name as the class. class Square Square(int w) x = w; ; int area () return (x*x);; ; void Square::set_values(int a) x = a; int Square::get_sidelen(void) const return x; int main () Square s(3); std::cout << "area: " << s.area(); // Output: area: 9 Constructors Constructors: Overloading Have the same name as the class. class Square Square(int w) x = w; ; int area () return (x*x);; ; void Square::set_values(int a) x = a; int Square::get_sidelen(void) const return x; int main () Square s; cout << "area: " << s.area(); // Output: area: 0 You can have several constructors for a class by overloading them. class Square Square(int w) x = w; ; Square() x = 0; ; int area () return (x*x);; ; Default constructor is defined for you: Square(); Constructors : Initialization Constructors: Warning Prefer member initializer list to assignment Square(int w):x(w); Array(int lowbound, int highbound):size(highbound-lowbound+1), lb ( lowbound ), hb (highbound), data_vector(size) ; Problematic? Why? List members in an initialization list in the order they were declared in the class If you implement no constructor, the compiler automatically generates a default constructor for you But if you write any constructors at all, the compiler does not supply a default constructor. 3

Copy Constructors Copy constructors: When is it called? Gets called in a number of situations. If you do not write one, the compiler automatically generates one for you. When the return value of a function has class type. Fraction process_fraction (int i, int j); When an argument has class type. A copy of the argument is made and passed to the function int numerator_process (Fraction f); When you use one object to initialize another object. Fraction a(1,3); Fraction b(a); Fraction b = a; Copy constructors Copy constructors Not used when a pointer to an object is passed. It s only called when a new copy of an existing object needs to be created. The syntax: class_name(class_name const &source) Const: Making a copy should not alter source. &: The function should not need to call another copy constructor! Copy Constructors: Example. class Point int x,y; int xx(void) const return x;; int yy(void) const return y;; Point(Point const &p) this->x = p.xx(); this->y = p.yy(); ; ; Destructors You can have many constructors but only one destructor. The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value. The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated. 4

// source: cplusplus.com class CRectangle int *width, *height; CRectangle (int,int); ~CRectangle (); int area () return (*width * (*height)); ; CRectangle::CRectangle (int a, int b) width = new int; height = new int; *width = a; *height = b; CRectangle::~CRectangle () delete width; delete height; int main () CRectangle rect (3,4), rectb (5,6); std::cout << "rect area: " << rect.area() << std::endl; std::cout << "rectb area: " << rectb.area() << std::endl; Output: rect area: 12 rectb area: 30 this pointer Useful when a member function manipulates two or more objects. It holds the address of the object for which the member function is invoked. It is always passed to a non-static member function. This ensures the right object is updated using member functions. Back to destructor example Assignment operators What will happen if we do: CRectangle r1(10,20),r2(30,40); r1 = r2; The default assignment operator generated by the compiler is called. What is wrong with that in this example? x = 4; 4 = x; // non-lvalue in assignment x = y = z = 8; z is assigned 8 first y is then assigned the value returned by (z = 8) which is 8. x is now assigned the value returned by (y = 8) which is 8 Assignment operators Assignment operators Complex x, y, z; x = (y = z); Writing this in equivalent functional form: x.operator=(y.operator=(z)); Square s1 = s2; The default behavior : Performs simple member by member copy. (This is the one generated by the compiler) Is the assignment operator the same thing as copy constructor? 5

Assignment Operator Assignment Operator Copy constructor initializes an object. Assignment operator copies values to an existing object. Hence, in some cases: Copy constructor has to do more work than assignment operator. Syntax: class_name& operator=(const class_name &source) const: Making an assignment should not alter source. &: The function should not need to call a copy constructor. An Example #include <cstring> class Buf Buf( char const* szbuffer, std::size_t sizeofbuffer ); Buf& operator=( const Buf & ); void Display() std::cout << buffer << std::endl; private: char* buffer; std::size_t SizeOfBuffer; ; Buf::Buf( char const* szbuffer, std::size_t sizeofbuffer ) sizeofbuffer++; // account for a NULL terminator buffer = new char[ sizeofbuffer ]; if (buffer) memcpy( buffer, szbuffer, sizeofbuffer ); SizeOfBuffer = sizeofbuffer; Buf& Buf::operator=( const Buf &otherbuf ) if( &otherbuf!= this ) if (buffer) delete [] buffer; SizeOfBuffer = strlen( otherbuf.buffer ) + 1; buffer = new char[sizeofbuffer]; memcpy( buffer, otherbuf.buffer, SizeOfBuffer ); return *this; int main() Buf mybuf( "my buffer", 10 ); Buf yourbuf( "your buffer", 12 ); // Display 'my buffer' mybuf.display(); // assignment opperator mybuf = yourbuf; // Display 'your buffer' mybuf.display(); Output: my buffer your buffer Place the common code used by the assignment operator and the copy constructor in a separate function and have each one call the function. This will make your code more compact and avoid duplication. A String class must copy a character string during the copy constructor and during an assignment. If we place this common code into a private member function void CopyString(const char* ptr); then both the copy constructor and assignment operator may call this routine to perform the copy rather than duplicate this code in each. From: http://www.acm.org/crossroads/xrds1-4/ovp.html 6

If your class has pointer data, you must provide an assignment operator. If writing an assignment operator, you must also write a copy constructor (and destructor?). The generated assignment operator performs member-wise assignment on any data members of your class. For pointer variables, we almost always do not want this because the data members of the copy will point to the same data as the copied object! Worse, if one of the objects is destroyed, the data is destroyed with it. A run-time error will occur the next time the remaining object tries to access the now nonexistent data. When dealing with pointers, Always implement the assignment operator for your class; do not let the compiler generate the default assignment operator. (Remember rule of 3) The compiler will generate a default assignment operator for your class if you do not provide one. In order to be in complete control of how your class operates, always provide an assignment operator. Check for assignment to self. Disaster can result if a variable is assigned to itself. Consider: X x; x = x; Suppose class X contains pointer data members that are dynamically allocated whenever an object is created. Assignment always modifies an existing object. The dynamic data will, therefore, be released before assigning the new value. If we do not check for assignment to self, the above assignment will delete the existing pointer data, and then try to copy the data that was previously deleted! The destructor must release any resources obtained by an object during its lifetime, not just those that were obtained during construction. Make the constructor as compact as possible to reduce overhead and to minimize errors during construction. 7