Download presentation
Presentation is loading. Please wait.
Published byRosalind Wade Modified over 5 years ago
1
ENERGY 211 / CME 211 Lecture 17 October 29, 2008
2
Constructors A constructor is a member function used to initialize an instance of a class Must have the same name as the class Cannot have a return type (even void) Can be overloaded Should throw an exception if anything goes wrong When a variable of a class type is declared, a constructor is called
3
Destructors A destructor is a member function that cleans up an instance's resources (files, memory) when instance is destroyed Must have the same name as the class, preceded by a ~ Cannot: have a return type, be overloaded, or accept arguments Should never throw an exception! Automatically called on de-allocation (e.g when containing scope is exited)
4
Copying Instances A copy constructor is used whenever instances of a class type are copied by the compiler (as in pass by value) A class always has a copy constructor implemented by the compiler, which simply copies the values of member variables from one instance to another Alternatively, you can define your own Declaration of copy constructor: class-name(const class-name&);
5
Overloading = For value types, should be able to assign values using =
The = operator must be overloaded: type& operator=(const type &); Can define overloads of = within a class to implement conversions from other types (like from char to string) In overloads of =, +=, etc. use return *this; this is address of the current object
6
Separate Header Files Typically, the declaration of a class is placed in a header file named after the class, with a .h extension Class declaration can include full definitions of member functions (such as simple constructors or destructor) Other member functions are usually defined in a separate implementation file named after the class, with a .cpp extension
7
Application Files An application file is a source file (with a .cpp extension) that uses classes to implement an application Must include header files for needed classes Can have multiple application files, but one must include main() function All application and implementation files must be compiled and linked together to create executable
8
Next Time Overloading operators Conversion operators Function objects
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.