Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes, Constructors, etc., in C++

Similar presentations


Presentation on theme: "Classes, Constructors, etc., in C++"— Presentation transcript:

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

2 Classes, Constructors, etc.
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 Field or method in Java CS-2303, A-Term 2012 Classes, Constructors, etc.

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

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

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

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

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

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

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

10 Interfaces versus Implementation
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) CS-2303, A-Term 2012 Classes, Constructors, etc.

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

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

13 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 Scope Resolution operator ‘::’ CS-2303, A-Term 2012 Classes, Constructors, etc.

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

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

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

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

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

19 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! i.e., “naked” CS-2303, A-Term 2012 Classes, Constructors, etc.

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

21 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 provides one if you do not! For each element in a new array! Compiler’s default simply calls constructors of data members of the class. CS-2303, A-Term 2012 Classes, Constructors, etc.

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

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

24 Classes, Constructors, etc.
Constructor Example /* * 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 /* * TreeNode.cpp */ #include "TreeNode.h“ // other methods TreeNode::TreeNode(const string &w){ ... } CS-2303, A-Term 2012 Classes, Constructors, etc.

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

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

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

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

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

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

31 Constructor Example (continued)
/* * 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 /* * 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 Invokes the string constructor to create a new const string object from the argument Widely used in the design of C++ classes CS-2303, A-Term 2012 Classes, Constructors, etc.

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

33 Common Programming Error
Not providing a member initializer for a const data member is a compilation error. CS-2303, A-Term 2012 Classes, Constructors, etc.

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

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

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

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

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

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

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

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

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

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


Download ppt "Classes, Constructors, etc., in C++"

Similar presentations


Ads by Google