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

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

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.

Object Oriented Programming(OOP).

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

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

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

IS0020 Program Design and Software Tools Midterm, Fall, 2004

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

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

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

Come and join us at WebLyceum

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

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

Programming, numerics and optimization

Introduction to Classes

Classes in C++98 and C++11

CS

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


Constructors & Destructors

Chapter 1: Object-Oriented Programming Using C++

CSC1322 Object-Oriented Programming Concepts

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

Object oriented programming with C++

C++ (classes) Hwansoo Han

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

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

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

OBJECT ORIENTED AND MULTICORE PROGRAMMING LABORATORY

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

Come and join us at WebLyceum

Function Overloading

G52CPP C++ Programming Lecture 13

CS201- Introduction to Programming Current Quizzes

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.

Constants, References

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

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

6.096 Introduction to C++ January (IAP) 2009

Constructors for classes

Pointers, Dynamic Data, and Reference Types

Initializing and Finalizing Objects

C++ 8. Constructors and Destructors


Inheritance, and Polymorphism.

Array Elements as Function Parameters

Constructor - example

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

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

Abstraction in Software Development

Function Declarations. Reference and Pointer Pitfalls. Overloaded Functions. Default Arguments

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

CS201 Latest Solved MCQs

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

CLASSES AND OBJECTS IN JAVA

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

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

CPSC 427: Object-Oriented Programming

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

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

CSE 333 Midterm Exam Nov. 3, 2017 Sample Solution

Object-Oriented Principles and Practice / C++

Object Oriented Design

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Common Misunderstandings from Exam 1 Material

OBJECT ORIENTED PROGRAMMING

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

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

Polymorphism Part 1 1

ROOT Course. Vincenzo Vitale, Dip. Fisica and INFN Roma 2

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

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

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

Scope. Scope is such an important thing that we ll review what we know about scope now:

Chapter 10 Introduction to Classes

Object-Oriented Principles and Practice / C++

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

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Pointers II. Class 31

An Introduction to C++

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

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

Lecture 18 Tao Wang 1

Programming in C++: Assignment Week 2

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

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Exercise1. // classes first example. #include <iostream> using namespace std; class Rectangle. int width, height; public: void set_values (int,int);

Programming in C++: Assignment Week 4

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

A brief introduction to C++

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Transcription:

Classes: Methods, Constructors, Destructors and Assignment For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Classes: Member functions // classes example void Square::set_values(int a) x = a; int Square::get_sidelen(void) const return x; Square s; s.set_values (3); cout << "area: " << s.area(); Member functions: Methods Objects : Reminder 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. 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. Objects : Reminder Objects: Reminder 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. The data members and member functions of an object have the same properties as the data members and member functions of its class. Square s1,s2; // each has separate copy of x 1

Assignment operator Variable assignment Square s3 = s2; By default, copying a class object is equivalent to copying all its elements including pointers. 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 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 & 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 cleans up and frees 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. // classes example Have the same name as the class. Square(int w) x = w; void Square::set_values(int a) x = a; int Square::get_sidelen(void) const return x; Square s(3); cout << "area: " << s.area(); Constructors Constructors: Overloading Have the same name as the class. Square() x = 0; void Square::set_values(int a) x = a; int Square::get_sidelen(void) const return x; Square s; cout << "area: " << s.area(); You can have several constructors for a class by overloading them. Square(int w) x = w; Square() x = 0; Default constructor is defined for you: Square() Constructors : Initialization Constructors: Warning Prefer initialization to assignment Square(int w):x(w) Array(int lowbound, int highbound):size(highboundlowbound+1), lb ( lowbound ), hb (highbound), data_vector(size) // Problematic? Why? List members in an initialization list in the order they were declared. 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); Copy constructors Not passed when a pointer to an object is passed. It s only called when a new copy of an existing object needs to be created. Copy constructors 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

// example on constructors and destructors (from cplusplus.com) class CRectangle int *width, *height; CRectangle (int,int); ~CRectangle (); int area () return (*width * (*height)); Pointers to functions Not in syllabus. CRectangle::CRectangle (int a, int b) width = new int; height = new int; *width = a; *height = b; CRectangle::~CRectangle () delete width; delete height; CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; this pointer Back to destructor example 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. 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? // example on constructors and destructors (from 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; CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; Assignment operators x = 4; 4 = x? // non-lvalue in assignment x = y = z = 8; Z is assigned 8 first Y is then assigned the value of returned by (z = 8) which is 8. x is now assigned the value returned by (y = 8) which is 8 5

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? 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. The 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 constructors. An Example #include <string.h> class Buf Buf( char* szbuffer, size_t sizeofbuffer ); Buf& operator=( const Buf & ); void Display() cout << buffer << endl; private: char* buffer; size_t SizeOfBuffer; Buf::Buf( char* szbuffer, 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; 6

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(); 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 If your class has pointer data, you must provide an assignment operator. If writing an assignment operator, you must also write a copy constructor. 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. Always implement the assignment operator for your class; do not let the compiler generate the default assignment operator. 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