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

Similar documents
class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

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

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

Instantiation of Template class

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

Assignment of Structs

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

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

2 ADT Programming User-defined abstract data types

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.

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Object-Oriented Programming

Chapter 13: Copy Control. Overview. Overview. Overview

Constructors for classes

Object-Oriented Principles and Practice / C++

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

04-19 Discussion Notes

Lecture 18 Tao Wang 1

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

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

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

CSI33 Data Structures

Chapter 10 Introduction to Classes

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

The Object Concept. Object-Oriented Programming Spring 2015

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

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++

Operator overloading. Conversions. friend. inline

CS304 Object Oriented Programming Final Term

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Chapter 10 :: Data Abstraction and Object Orientation

Short Notes of CS201

CPSC 427: Object-Oriented Programming

CS201 - Introduction to Programming Glossary By

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

Midterm Review. PIC 10B Spring 2018

B16 Object Oriented Programming

CS201 Some Important Definitions

Part 3. Why do we need both of them? The object-oriented programming paradigm (OOP) Two kinds of object. Important Special Kinds of Member Function

An Introduction to C++

Fast Introduction to Object Oriented Programming and C++

7.1 Optional Parameters

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

Chapter 9 :: Data Abstraction and Object Orientation

CS105 C++ Lecture 7. More on Classes, Inheritance

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

B16 Object Oriented Programming

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

G52CPP C++ Programming Lecture 13

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

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

CSE 307: Principles of Programming Languages

CSC1322 Object-Oriented Programming Concepts

C++ Important Questions with Answers

QUIZ Friends class Y;

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

COMP6771 Advanced C++ Programming

COSC 2P95 Lab 5 Object Orientation

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

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

Programming, numerics and optimization

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Special Member Functions

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

Functions, Pointers, and the Basics of C++ Classes

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

Introduction Of Classes ( OOPS )

Smart Pointers. Some slides from Internet

C++ Functions. Procedural-based Programming. what s a functions

Computer Science II CSci 1200 Lecture 18 Operators and Friends

Introduction to Programming Using Java (98-388)

Object Oriented Design

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

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

ALL ABOUT POINTERS C/C++ POINTERS

Assignment operator string class c++ Assignment operator string class c++.zip

CS24 Week 3 Lecture 1

CSc 328, Spring 2004 Final Examination May 12, 2004

Pointers and References

Programming in C and C++

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

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

SFU CMPT Topic: Class Templates

OBJECT ORIENTED PROGRAMMING

Constructor - example

C++ Constructor Insanity

CS3157: Advanced Programming. Outline

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

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

THE EVALUATION OF OPERANDS AND ITS PROBLEMS IN C++

CSE 431S Type Checking. Washington University Spring 2013

Constants, References

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

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

Copy Constructors & Destructors

Transcription:

Polynomial Class Polynomial(); Polynomial(const string& N, const vector<int>& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const Polynomial& RHS) const; Polynomial Derivative() const; Polynomial Antiderivative() const; int Integral(int a, int b) const; int operator()(int x) const; string getname() const; void setname(const string& N); ~Polynomial(); private: string Name; vector<int> P; 1 See the CS 2704 notes on C++ Class Basics for more details and examples. Some Immediate Differences 2 First, some differences versus Java: - C++ classes are not specified with any access control on the class itself. - C++ class declarations are statements, and hence are terminated with a semicolon. - C++ class member functions are not usually implemented within the class declaration; rather the declaration is placed in a header file and the coresponding implementation is placed in a cpp file. - Members of a C++ class are private unless explicitly specified otherwise. Polynomial(); Polynomial(const string& N, const vector<int>& C); private: string Name; vector<int> P;

Implementing Member Functions 3 Since the member function implementation is not incorporated into the class declaration, we need some extra syntax to tie the implementation to the class: Polynomial::Polynomial(const string& N, const vector<int>& C) { string Polynomial::getName() const { const Member Functions 4 Member functions that do not modify any data members of the class can (and should) be declared with the modifier const. const member functions: - are prevented at compile-time from modifying any data members of the class - may be invoked even on objects that are themselves declared as const Accessor functions are typically const. So are member functions and operators that create new objects from old ones. Polynomial Derivative() const; Polynomial Antiderivative() const; int Integral(int a, int b) const; string getname() const;

C++ Operators 5 In C++, operators may be overloaded, extending the language to apply familiar syntax to new types with natural semantics. Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const Polynomial& RHS) const; int operator()(int x) const; Assuming that P, Q and R are objects of type Polynomial, all of the following are valid and have precisely the meaning you would expect: P = Q + R; P = Q * 5; int Result = P(42); We will explore operator overloading in great depth, but that will come a bit later. Destructors 6 C++ classes may include a special member function, whose name is the same as the class, preceded by a tilde character ('~'). This member is called the class destructor. Whenever the lifetime of an object comes to an end, its destructor is automatically invoked. Destructors are rarely invoked explicitly. The most common use for a destructor is to encapsulate the logic needed to deallocate any dynamic content for which an object is responsible. Destructors may also be used for logging and other bookkeeping purposes. ~Polynomial();

What's Automatic? C++ classes have certain features automatically. 7 If you do not provide any constructors, a default constructor will be created by the compiler; however it will be trivial (i.e., it will do nothing). If you do not provide a destructor, a trivial one will be supplied by the compiler. If you do not provide a copy constructor or assignment operator, simple non-trivial versions will be supplied by the compiler. More about these later Every C++ object has an implied data member named this, which is a pointer to the object itself. Type Conversion Issues 8 Any class constructor that takes a single value may be viewed as defining a conversion from objects of that type to objects of the class type. For example: class Foo { Foo(int x); // converts int to Foo Foo A(12); A = 42; // fine, just what we expect // seemingly meaningless, right? The last statement is, in fact, legal code. The Foo constructor is invoked automatically when the compiler attempts to make sense of the statement. This results in the creation of a new Foo object, which is then assigned to A. This is probably not what we would want. If not, the automatic (or implicit) invocation of the constructor can be prevented: class Foo { explicit Foo(int x);

Copying Objects 9 What happens when an object is copied? By default, copying is performed either by a copy constructor or an assignment operator, depending on the context in which the copy is made. The automatic copy constructor and assignment operator are very simple. They just copy the data members from the source object into the target object. This is perfectly satisfactory for many classes: class Complex { private: double Real; double Imaginary; Complex X(4.2, 7.3); Complex Y; Y = X; This is called making a shallow copy because the logic does not extend beyond the level of the class data members. Shallow Copy Problem 10 But consider: class charbuffer { charbuffer(int Sz) { Buff = new char[sz]; private: char *Buff; The effect is less than desirable: charbuffer X(100); charbuffer Y; Y = X; X Buff Y Buff Just imagine what the destructor for the class charbuffer would do

Deep Copy 11 Clearly what we would really want would be for the assignment to have produced this situation: X Buff Y Buff And, of course, we would also want the contents of the array belonging to X to be duplicated in the array that belongs to Y. This is called making a deep copy. Since the automatic copy support for a C++ class does not make a deep copy, it must be the responsibility of the class to provide such support. Implementing a Deep Copy Assignment 12 For the previous example, what is needed is for the class charbuffer to include an implementation of the assignment operator that does, in fact, perform a deep copy: charbuffer& charbuffer::operator=(const charbuffer& RHS) { if ( this == &RHS ) // if self-assignment, no copying return *this; delete [] Buff; Size = RHS.Size; // discard dynamic stuff in LHS object // copy static stuff into LHS object Buff = new char[size]; // make new array for LHS object // copy array contents from RHS object into LHS object for (unsigned int Pos = 0; Pos < Size; Pos++) Buff[Pos] = RHS.Buff[Pos]; return *this; // return RHS object (by reference)

Deep Copy Constructor 13 A copy constructor is just a constructor for a class X that takes an object of type X as its only parameter: charbuffer::charbuffer(const charbuffer& Source) { Size = Source.Size; // copy static stuff into new object Buff = new char[size]; // make new array for new object // copy array contents from source object into new object for (unsigned int Pos = 0; Pos < Size; Pos++) Buff[Pos] = Source.Buff[Pos]; Note that the body of the copy constructor is a subset of the body of the assignment operator. This makes life simple. Destructor Redux 14 As noted before, the most common task for a class destructor is simply to deallocate anything an object of the class has allocated dynamically and retained control of: charbuffer::~charbuffer() { delete [] Buff; Since this in invoked automatically whenever the lifetime of a charbuffer object comes to an end, and this does deallocate everything such an object could possibly have obtained dynamically, this would seem to guarantee that charbuffer objects will not cause memory leaks. In this matter, things really are as they seem.

Automatic Cascading Effects 15 When a shallow copy of an object is made, any data members that are objects are copied using the copy logic provided by their classes. That's why the Polynomial class did not need its own copy constructor or assignment operator. When an object is destructed, any data members that are objects have their own destructors invoked immediately after the destructor for the containing object. That's why the Polynomial class did not need a user-defined destructor. When an object is constructed, by default any data members that are objects have their own default constructors invoked immediately before the constructor for the containing object is executed. Default Arguments 16 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>()); You may specify defaults for some parameters and not specify defaults for others; however, all parameters w/o defaults must precede those that have defaults. The default value is used if the call does not specify a corresponding actual parameter: Polynomial F("F", vectorofcoefficients); Polynomial G("G"); Polynomial H; Note that the modified constructor now plays the role of a default constructor.

Implicit Inline Functions 17 C++ class member functions may also be implemented within the class declaration: string getname() const { return Name; // inline function This may be considered bad practice since it exposes the details of the implementation to the user of the class. However, this has an interesting side effect. Functions implemented within the class declaration are said to be inline. The C++ compiler may optimize the compiled code by replacing calls to an inline function with the (suitably modified) function body, eliminating some work on the runtime stack. Explicit Inline Functions 18 An alternative is to specify the function is to be inlined by adding syntax to the function implementation: // Polynomial.cpp #include "Polynomial.h" inline string Polynomial::getName() const { return Name; This has the same effect, but does not expose the implementation in the header file. Note: in any case, the compiler is free to ignore the request and NOT replace calls to the function with its body.