Lecture 12 Destructors “Absolute C++” Chapters 10.3, 15.2.

Slides:



Advertisements
Similar presentations
Objects and Classes Part II
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Pointers “Absolute C++” Section 10.1
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Classes Separating interface from implementation
Lecture 5 Constructors Operator Overloads “Absolute C++” Chapters 7.1,8.1,8.2.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
Lecture 10 Inheritance “Absolute C++” Chapter 14.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Dynamically Allocated Arrays December 4, Skip the Rest of this PowerPoint.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Dynamic Memory. We will follow different order from Course Book We will follow different order from Course Book First we will cover Sect The new.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 CSC241: Object Oriented Programming Lecture No 03.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Introduction to Object Oriented Programming Chapter 10.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Learners Support Publications Constructors and Destructors.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Pointers and References. Pointers & Memory 0x000x040x080x0B0x100x140x180x1B0x20.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Yan Shi CS/SE 2630 Lecture Notes
Constructors and Destructors
Learning Objectives Pointers as dada members
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Lecture 7 Arrays, Dynamic Arrays & Copy Constructors “Absolute C++”
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
group work #hifiTeam
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
CMSC 341 Prof. Michael Neary
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
CISC/CMPE320 - Prof. McLeod
9-10 Classes: A Deeper Look.
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
CS 144 Advanced C++ Programming April 30 Class Meeting
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

Lecture 12 Destructors “Absolute C++” Chapters 10.3, 15.2

Destructors Quick review of constructors: They’re called when an object is created You may perform one-time initializations in constructors Memory allocation member variable initializations You may define multiple constructors Each may take a varying number of parameters If you do not define a constructor for a given class, C++ will define one for you (that basically does nothing). Destructors are called whenever an object is destroyed (or just before destruction) Destructors give you a place to: Free memory allocated in a constructor Release system resources (Windows, disk drives, etc.)

Destructors A destructor is declared by declaring a member function which has the same name as the class (like a constructor) only prefixing it with a tilde (~) character. There is ever only one destructor per class. Destructors do not take arguments. It is not usually necessary to zero out member variables The destructor is called right before the object goes away, so dangling values in member variables shouldn’t matter. Let’s look at a class definition that contains a destructor…

Destructors The following class simply shows a constructor and a destructor. We’ll print out messages from each so that we know when the runtime environment is executing them… class SomeClass { public: SomeClass() { cout << “We’re in the constructor” << endl; } ~SomeClass() { cout << “We’re in the destructor” << endl; } };

Demonstration #1 A Simple Destructor

Destructors The best way to determine if you need a destructor in a given class is to look at any constructors which might be present. Remember the following modified version of Course from last lecture: class Course { public: Course(); Course(string theCourse,string theInstructor,int classSize); private: string courseName; string instructor; int size; Student *studentList; int nextStudent; };

Destructors When looking at the definition of the constructors, we see the following: Course::Course() { courseName = “unknown”; instructor = “unknown”; size = nextStudent = 0; studentList = NULL; } Course::Course(string theCourseName,string theInstructor, int classSize):courseName(theCourseName), instructor(theInstructor),size(classSize), nextStudent(0) { studentList = new Student[size]; }

Destructors In the overloaded constructor that takes three arguments, we are dynamically allocating memory. Since this memory needs to be freed somewhere (presumably when we’re done with the object) a destructor seems like a logical choice. class Course { public: // Constructors Course(); Course(string theCourse,string theInstructor,int classSize); // Destructor ~Course(); // Notice the ‘`’ in front of the member name // Rest of class definition here… };

Destructors Just like constructors, destructors can be defined either inside the class definition or in the corresponding.cpp file. Using the latter, we might see this: Course::~Course() { // Check to see if studentList has allocated memory if (studentList) { // it does! Delete the dynamically allocated array delete [] studentList; }

Demonstration #2 Course’s Destructor

Destructors and Inheritance What happens if I want to derive a class from Course? Take a more specific computer science course: class CSCourse : public Course { public: CSCourse():Course(),csugAccount(false){} CSCourse(string theCourse,string theInstructor, int classSize, bool argCSUGaccount): Course(theCourse,theInstructor,classSize), csugAccount(argCSUGaccount){} bool getsCSUGaccount() { return csugAccount; } private: bool csugAccount; };

Demonstration #3 Inherited Destructor

Overriding Destructors? If CSCourse had it’s own destructor, would it override Course’s? Suppose we arbitrarily define a destructor for URL: What will happen now when we run our simple program? class CSCourse : public Course { public: CSCourse():Course(),csugAccount(false){} CSCourse(string theCourse,string theInstructor, int classSize, bool argCSUGaccount): Course(theCourse,theInstructor,classSize), csugAccount(argCSUGaccount){} ~CSCourse() { cout << “In CSCourse destructor” << endl; } bool getsCSUGaccount() { return csugAccount; } private: bool csugAccount; };

Demonstration #4 Destructors in base and derived Classes

Overriding Destructors? (cont) int main() { CSCourse *myCSCourse = new CSCourse(); Course *aCourse; aCourse = myCSCourse;; delete aCourse; } OK, why did it call both destructors? Because it’s the “right thing to do” :-) Destructors are not “overridden” by derived classes. When an object is destroyed, the destructor for that class is called followed by the destructors for any base classes. Does this mean we don’t need to worry about virtual destructors? No, we do. Consider the following code:

Demonstration #5 Virtual Destructors?

Overriding Destructors? (cont) OK, so how do we declare a virtual destructor? Remember, it is the destructor in the base class that needs to be declared as virtual. So, if we declare Course’s destructor to be virtual, we’ll get the desired behavior...

Demonstration #6 Virtual Destructors!

Automatically Generated Functions If you don’t define a constructor, destructor or copy constructor, C++ will define a “default” one for you. A default constructor does nothing A default destructor does nothing A default copy constructor will populate all the member variables of the new class with values found in all the member variables of the class being copied from. Why do we care? Consider the following code: Course MakeACourse(string name,string instructor,int size) { Course returnCourse(name,instructor,size); return returnCourse; }

Automatically Generated Functions (cont) Course MakeACourse(string name,string instructor,int size) { Course returnCourse(name,instructor,size); return returnCourse; } When we return returnCourse the compiler actually makes a copy of returnCourse on the stack and then returnCourse’s destructor is called. When returnCourse’s destructor is called all dynamically allocated memory is freed. That leaves the copy of returnCourse on the stack with a pointer to deallocated memory waiting to be assigned to whatever variable is receiving it in the calling function… OUCH! Next time we’ll work on fixing that problem...

Lecture 12 Final Thoughts