classes, constructors, etc.web.cs.wpi.edu/.../lectures_a12/week4_classesconstructors.pdf ·...

43
Worcester Polytechnic Institute Classes, Constructors, etc., in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) Classes, Constructors, etc. CS-2303, A-Term 2012 1

Upload: others

Post on 31-May-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute

Classes, Constructors, etc., in C++

Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5th and 6th editions, by Deitel and Deitel)

Classes, Constructors, etc. CS-2303, A-Term 2012 1

Page 2: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Review struct A class in C++ in which all members are by default public Stylistically, may be used like structs in C.

class Definition of a new type of data structure, including member functions

and member data Similar to Java

Definitions Member: one of the data items or functions declared within the body

of a class Object: an instance of a class, occupies memory, data values are

populated in the instance

Classes, Constructors, etc. CS-2303, A-Term 2012 2

Field or method in Java

Page 3: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Recommended class structure for PA4 class TreeNode Defines the nodes of the binary tree Constructor, destructor Methods for accessing fields, updating links, comparing strings,

incrementing counts

class BinaryTree Includes a root pointing to a TreeNode Methods for inserting data, traversing and outputting data

Classes, Constructors, etc. CS-2303, A-Term 2012 3

Page 4: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

TreeNode

class TreeNode { public: int incr(); int getCount(); string getWord(); int compare(const string &w2); TreeNode *setleft(TreeNode *t); TreeNode *setright(TreeNode *t); TreeNode *getleft(); TreeNode *getright();

// non-default constructor TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Classes, Constructors, etc. CS-2303, A-Term 2012 4

Page 5: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

BinaryTree class BinaryTree{ public: TreeNode *AddNode(const string &word); int getTotalNodes(); void PrintTree(ostream &output); BinaryTree(); //Default constructor ~BinaryTree(); //Destructor private: static int totalNodes; void PrintTree(TreeNode *subtree, ostream &output); TreeNode *AddNode(TreeNode *subtree, const string &word); TreeNode *root; }; // class BinaryTree

Classes, Constructors, etc. CS-2303, A-Term 2012 5

Overloaded functions

Page 6: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Note on Overloaded Functions

A function may share a name with other functions but have different parameter list! E.g., AddNode() and PrintTree() in BinaryTree class E.g., sqrt() applied to double or complex

When compiler detects overloading, it mangles the names of the functions AddNode(const string &word) → AddNode_$string AddNode(TreeNode *subtree, const string &word) →

AddNode_$$subtree_$string … thereby making them functions with different names!

Classes, Constructors, etc. CS-2303, A-Term 2012 6

Page 7: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute

Questions?

Classes, Constructors, etc. CS-2303, A-Term 2012 7

Page 8: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

C++ Program Structure Typical C++ Programs consist of:– A function main() One or more class definitions

Each defining data members and member functions

One of more class implementations

Optionally:– One or more static objects One or more non-member functions

Classes, Constructors, etc. CS-2303, A-Term 2012 8

Page 9: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Stylistic guidance

Each class definition should have its own .h file Separate from all other class definitions

Each class should have its own implementation in

one or more .cpp files Separate from all other class implementations

Plus one or more additional .cpp files For main(), etc.

Required for this course!

Classes, Constructors, etc. CS-2303, A-Term 2012 9

Page 10: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Interfaces versus Implementation

Interface Describes what services a class’s clients can use and

how to request those services. without revealing how the class carries out the services. a class definition listing only public member function

prototypes.

A class’s interface consists of the class’s public member functions (services).

Defined in class header file (.h)

Classes, Constructors, etc. CS-2303, A-Term 2012 10

Page 11: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Interfaces vs.Implementation

Implementation of member functions In a separate source-code file for a class

Use binary scope resolution operator (::) to tie each member function to the class definition.

Implementation details are hidden. Client code does not need to know the

implementation.

Classes, Constructors, etc. CS-2303, A-Term 2012 11

Page 12: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Example — TreeNode interface /* * TreeNode.h */ #include <string> class TreeNode { public: int incr(); int getCount(); // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Classes, Constructors, etc. 12 CS-2303, A-Term 2012

Page 13: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Example — TreeNode implementation

/* * TreeNode.cpp */ #include "TreeNode.h" int TreeNode::incr(){ return ++count; } // int TreeNode::incr() int TreeNode::getCount(){ return count; } // int TreeNode::getCount() TreeNode::~TreeNode{ delete left; delete right; delete word; } // TreeNode::~TreeNode

Classes, Constructors, etc. 13 CS-2303, A-Term 2012

Scope Resolution operator ‘::’

Page 14: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Stylistic guidance

Each class definition should have its own .h file Separate from all other class definitions

Each class should have its own implementation in one or more .cpp files Separate from all other class implementations

Plus one or more additional .cpp files For main(), etc.

Classes, Constructors, etc. CS-2303, A-Term 2012 14

For reusability!

Page 15: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Software Engineering Observation

As a rule of thumb, data members should be declared private

Member functions should be declared public Except member functions that are accessed only by

other member functions of the class.

Often useful to have get() and set() member functions To access private members in controlled ways

Classes, Constructors, etc. CS-2303, A-Term 2012 15

Page 16: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Namespace

A logical grouping of names

… to set them apart from other names

… to avoid conflicts among similar names

See §8.2

Each class is its own namespace Other namespaces can be defined — §11.2

Classes, Constructors, etc. CS-2303, A-Term 2012 16

Page 17: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Scope Resolution Operator

int TreeNode::incr() int TreeNode::getCount() TreeNode::TreeNode(const string &w); The methods named incr(), getCount() and TreeNode()

defined in the class TreeNode

std::cout The object cout that is declared in namespace std

Classes, Constructors, etc. CS-2303, A-Term 2012 17

Page 18: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

“Using” Directive

Make one or more names from a namespace available in current scope Without specifying scope resolution operator each time

E.g., using std::cout;

using std::cin; using std::endl;

Classes, Constructors, etc. CS-2303, A-Term 2012 18

These names may now be used in current scope without qualification

Page 19: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Common C++ Programming Error Forgetting to say “using” You get undeclared identifiers Even though you include the appropriate header file!

Using std Bad style Makes all names in namespace std visible … whether you need them or not!

Classes, Constructors, etc. CS-2303, A-Term 2012 19

i.e., “naked”

Page 20: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute

Questions?

Classes, Constructors, etc. CS-2303, A-Term 2012 20

Page 21: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructors and Destructors

Constructor:– a member function used to initialize the data of an object of a class Same name as class itself Cannot return anything, not even void A class may define more than one constructor

With different parameter lists Default constructor has no parameters

Called automatically When class object is declared as an automatic or static

variable By new operator

Classes, Constructors, etc. CS-2303, A-Term 2012 21

Compiler provides one if you do not!

Compiler’s default simply calls constructors of data members of the class.

For each element in a new array!

Page 22: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructors and Destructors (continued)

Destructor:– a function used to clean up an object of a class prior to deleting that object Class name preceeded by '~' No parameters, no result

Called automatically When function exits scope of automatic class object By delete or delete[] operator

Classes, Constructors, etc. CS-2303, A-Term 2012 22

Compiler provides one if you do not!

Compiler’s default simply calls destructors of data members of the class.

delete[] cleans up each element of array

Page 23: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructors and Destructors (continued)

Constructors – Similar to Java

Destructors – No counterpart in Java

Purpose of Destructors Free dynamic storage pointed to only by members of

object Reduce reference count when object disappears Safely close things – e.g., files …

Classes, Constructors, etc. CS-2303, A-Term 2012 23

Page 24: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor Example

/* * TreeNode.cpp */ #include "TreeNode.h“ // other methods TreeNode::TreeNode(const string &w){ ... }

Classes, Constructors, etc. 24 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Page 25: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

What Must Constructor Do?

(Allocate memory for whole object) Done before constructor method is called

Initialize left, right members To zero (i.e., NULL)

Initialize count member To 1

Create a string object word and initialize How?

Classes, Constructors, etc. CS-2303, A-Term 2012 25

Page 26: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor Example (continued)

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; }

Classes, Constructors, etc. 26 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Page 27: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor Example (continued)

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; }

Classes, Constructors, etc. 27 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

string class supports '=' operator (Does the right thing!)

Page 28: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor Example (continued)

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; }

Classes, Constructors, etc. 28 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode Another problem

Page 29: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor Example (continued)

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; }

Classes, Constructors, etc. 29 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Member “word” is const ⇒ may not be on left any assignment! Not even in constructors

Page 30: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Solution – Initializer List

A list of member-value pairs Or member-constructor pairs

Between the () of the constructor header and the {} of the constructor body Preceded by ':' and separated by ','

Classes, Constructors, etc. CS-2303, A-Term 2012 30

Page 31: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor Example (continued)

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w) :word(newWord), //initialize word count(1), //initialize count left(0), //initialize left right(0) { /* rest of constructor body */ } // TreeNode constructor

Classes, Constructors, etc. 31 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Widely used in the design of C++ classes

Page 32: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

When are Constructors Called?

Global Scope — I.e., objects declared outside of any function

Before main() is called! Function or Block Scope — I.e., automatic variables and

constants When execution reaches point where object is declared For static objects, the first time execution reaches point

where object is declared Class Scope — I.e., data members of a class

When class constructor executes initialization list (or enters block scope of constructor function)

Dynamic objects — I.e., objects created by new Constructor is invoked by new operator

Classes, Constructors, etc. CS-2303, A-Term 2012 32

Page 33: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Common Programming Error

Not providing a member initializer for a const data member is a compilation error.

Classes, Constructors, etc. CS-2303, A-Term 2012 33

Page 34: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Common Programming Error

A compilation error occurs if a member object is not initialized with a member

initializer and the member object’s class does not provide a default

constructor Even if member object’s class defines one or more

constructors, but none is a default constructor!

Classes, Constructors, etc. CS-2303, A-Term 2012 34

Page 35: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute

Questions?

Classes, Constructors, etc. CS-2303, A-Term 2012 35

Page 36: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Destructors

The opposite of constructors

Called to clean up objects before deleting them Very important if your class has members that are

objects of other classes E.g., string

Dynamically allocates array of characters to hold the string itself

Must be freed before string object can be deleted

Classes, Constructors, etc. CS-2303, A-Term 2012 36

Page 37: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Destructor Example

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w) :word(newWord), //initialize word count(1), //initialize count left(0), //initialize left right(0) { } // TreeNode constructor TreeNode::~TreeNode() { if (left) delete left; if (right) delete right; left = right = 0; } // TreeNode destructor

Classes, Constructors, etc. 37 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Page 38: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Destructor Example

/* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w) :word(newWord), //initialize word count(1), //initialize count left(0), //initialize left right(0) { } // TreeNode constructor TreeNode::~TreeNode() { if (left) delete left; if (right) delete right; left = right = 0; } // TreeNode destructor

Classes, Constructors, etc. 38 CS-2303, A-Term 2012

/* * TreeNode.h */ #include <string> class TreeNode { public: … // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode

Note: destructor for string word and for count are called automatically (because these are in class scope).

Destructors for left and right have to be called forcibly, because those object were allocated dynamically

Page 39: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

When are Destructors Called?

In opposite order of constructors (mostly)

Dynamic objects Invoked by delete operator

Class scope — I.e., data members of a class

Invoked by destructor of class object Function or Block Scope

When just before leaving the scope Global Scope

After main() has returned

Classes, Constructors, etc. CS-2303, A-Term 2012 39

Page 40: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Exceptions to calling destructors static objects in function or block scope

After main() has returned but before calling destructors of objects in Global Scope

exit() function Destructors of automatic objects are not called Usually means abnormal termination of program, file cannot

be opened, etc.

abort() function No destructors are called Usually means serious error, etc.

Classes, Constructors, etc. CS-2303, A-Term 2012 40

Page 41: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Dynamically Allocated Objects Always use new operator (as in Java)

Returns pointer to object (as with malloc() in C) Never use malloc()

There is a lot more to creating an object in C++ than simply allocating memory

new calls malloc() to allocate memory, calls constructor, sets up inheritance, finds the right polymorphic functions, etc.

Always use delete or delete[] operator Invokes destructor, cleans up, calls free(), etc. Takes pointer to object

Never call free() directly For same reasons not to call malloc(); memory leaks, etc.

Classes, Constructors, etc. CS-2303, A-Term 2012 41

Page 42: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute Worcester Polytechnic Institute

Constructor-Destructor Summary

Constructors are a big deal A class may have many constructors Different parameter lists

Destructors are a bigger deal Class only has one destructor Must tidy up everything after itself

– Include delete of member objects

Classes, Constructors, etc. CS-2303, A-Term 2012 42

Page 43: Classes, Constructors, etc.web.cs.wpi.edu/.../Lectures_A12/Week4_ClassesConstructors.pdf · Constructor, destructor Methods for accessing fields, updating links, comparing strings,

Carnegie Mellon Worcester Polytechnic Institute

Questions?

Classes, Constructors, etc. CS-2303, A-Term 2012 43