Classes, Constructors, etc., in C++

Similar documents
Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Programming Assignment #4 Binary Trees in C++

Containers and the Standard Template Library (STL)

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Derived Classes in C++

A Deeper Look at Classes

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Linked Lists in C and C++

Your first C and C++ programs

Exception Handling in C++

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Binary Trees (and Big O notation)

EL2310 Scientific Programming

CSE 303: Concepts and Tools for Software Development

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

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Introduction to C++ Introduction to C++ 1

Structures, Unions, and Typedefs

EL2310 Scientific Programming

Fast Introduction to Object Oriented Programming and C++

Object Oriented Programming. Solved MCQs - Part 2

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

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

ECE 244 Programming Fundamentals Fall Lab Assignment #5: Binary Search Trees

An Introduction to C++

EL2310 Scientific Programming

AN OVERVIEW OF C++ 1

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

Object-Oriented Programming

CS

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

CS201 Some Important Definitions

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

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

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

Programming in C and C++

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

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

Arrays and Pointers in C & C++

STRUCTURING OF PROGRAM

Tree Travsersals and BST Iterators

Introducing C++ to Java Programmers

CS 376b Computer Vision

Intermediate Programming, Spring 2017*

CS250 Final Review Questions

PHY4321 Summary Notes

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

Exam Informatik D-MATH/D-PHYS :00 11:00

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Interview Questions of C++

Introduction to C++ Systems Programming


MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Final Examination 8:30 AM, Wednesday, April 18, 2012

Ch. 12: Operator Overloading

Run Time Environment

lecture14: Tree Traversals

Absolute C++ Walter Savitch

CS 11 C++ track: lecture 1

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

Introduction to Programming session 24

COMP 2355 Introduction to Systems Programming

CS 241 Data Organization Binary Trees

This examination has 11 pages. Check that you have a complete paper.

CS93SI Handout 04 Spring 2006 Apr Review Answers

C++_ MARKS 40 MIN

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

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

Set Implementation Version 1

Chapter 11. Abstract Data Types and Encapsulation Concepts

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

CE221 Programming in C++ Part 1 Introduction

IS 0020 Program Design and Software Tools

CMSC 341 Lecture 10 Binary Search Trees

Chapter 15 - C++ As A "Better C"

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

PIC 10A Objects/Classes

CS3157: Advanced Programming. Outline

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

C++ 8. Constructors and Destructors

Fundamentals of Programming Session 24

CS201- Introduction to Programming Current Quizzes

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Lecture 18 Tao Wang 1

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 13

COIMBATORE EDUCATIONAL DISTRICT

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

Crash Course into. Prof. Dr. Renato Pajarola

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Example Final Questions Instructions

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Transcription:

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

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 Field or method in Java Object: an instance of a class, occupies memory, data values are populated in the instance 2

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 3

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 4

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

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

Questions? 7

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 8

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

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

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

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 CS-2303, A-Term 2012 Classes, Constructors, etc. 12

Example TreeNode implementation /* * TreeNode.cpp */ #include "TreeNode.h" int TreeNode::incr(){ return ++count; } // int TreeNode::incr() int TreeNode::getCount(){ return count; } // int TreeNode::getCount() Scope Resolution operator :: TreeNode::~TreeNode{ delete left; delete right; delete word; } // TreeNode::~TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 13

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. For reusability! 14

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 15

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 16

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 17

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; These names may now be used in current scope without qualification 18

Common C++ Programming Error Forgetting to say using You get undeclared identifiers Even though you include the appropriate header file! Using std i.e., naked Bad style Makes all names in namespace std visible whether you need them or not! 19

Questions? 20

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 Compiler s default simply calls constructors of data members of the class. Compiler provides one if you do not! For each element in a new array! 21

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 Compiler provides one if you do not! Called automatically When function exits scope of automatic class object By delete or delete[] operator Compiler s default simply calls destructors of data members of the class. delete[] cleans up each element of array 22

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 23

Constructor Example /* * TreeNode.h */ #include <string> /* * TreeNode.cpp */ #include "TreeNode.h // other methods TreeNode::TreeNode(const string &w){... } class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 24

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? 25

Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } /* * 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 CS-2303, A-Term 2012 Classes, Constructors, etc. 26

Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); string class supports '=' operator (Does the right thing!) private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 27

Constructor Example (continued) /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } Another problem /* * 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 CS-2303, A-Term 2012 Classes, Constructors, etc. 28

Constructor Example (continued) Member word is const may not be on left any assignment! Not even in constructors /* * TreeNode.cpp */ #include "TreeNode.h" TreeNode::TreeNode(const string &w){ count = 1; left = 0; // null pointer right = 0; word = w; } /* * 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 CS-2303, A-Term 2012 Classes, Constructors, etc. 29

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 ',' 30

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 /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; CS-2303, A-Term 2012 }; // class TreeNode Widely used in the design of C++ classes Classes, Constructors, etc. 31

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 32

Common Programming Error Not providing a member initializer for a const data member is a compilation error. 33

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

Questions? 35

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 36

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 /* * 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 CS-2303, A-Term 2012 Classes, Constructors, etc. 37

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 /* * TreeNode.h */ #include <string> class TreeNode { public: // other methods Worcester Polytechnic Carnegie Institute Mellon 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 TreeNode(const string &w); ~TreeNode(); private: const string word; int count; TreeNode *left, *right; }; // class TreeNode CS-2303, A-Term 2012 Classes, Constructors, etc. 38

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 39

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

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

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 42

Questions? 43