Download presentation
Presentation is loading. Please wait.
1
Monday, 10/14/02, Slide #1 CS 106 Intro to CS 1 Monday, 10/14/02 QUESTIONS?? Today: More on classes! Reading: None new Exercises: Implement and test a function Argument for the class Complex, as discussed today. New files/handouts: None new
2
Monday, 10/14/02, Slide #2 Constructors: Different kinds Generally, should always have a default constructor: ClassName( ) { }; Empty body can be defined ‘in-line’ in header file Should include constructors to handle each of the ways that clients might specify initial values. Generally declare in header file, define in initialization file: Complex(float initReal, float initImag); Lets user supply initial values for real and imaginary parts Complex(float initReal); Lets user supply initial value for real part (imaginary part is set to zero) This constructor can also be viewed as a type conversion function -- changing a float object to type Complex
3
Monday, 10/14/02, Slide #3 Default parameters: Making constructors (and other functions) more flexible Here is another way to declare and define the initializing constructor for Complex: In header file: Complex (double initReal = 0; double initImag = 0); In implementation file: Complex::Complex(double initReal, double initImag) {real = initReal; imag = initImag; } Permits user to omit arguments with default values: all or leave off one or more rightmost arguments Note difference!
4
Monday, 10/14/02, Slide #4 More on constructors with default parameters Using previous constructor, following client declarations are all legal: Complex a(1.1, 2.2);// a = 1.1 + 2.2 i Complex b(3.3);// b = 3.3 + 0 i Complex c; // c = 0 + 0 i This constructor serves as initializing and default constructor and conversion function for real numbers! Can’t omit earlier arguments and keep later ones: Complex d(, 4.4) //illegal -- missing 1st argument
5
Monday, 10/14/02, Slide #5 Kinds of member functions Constructors and destructors: To create and destroy class objects Destructors deallocate memory when a class object goes out of scope -- simple destructors are provided by the system -- these are fine for us right now. Inspectors: To return attributes of an object Mutators: To set or change attributes of an object Facilitators: To use an object to perform an action
6
Monday, 10/14/02, Slide #6 Examples for class Complex Inspectors: To return attributes of an object Possible Complex inspectors might return: real part, imaginary part, magnitude, angle with x-axis Mutators: To set or change attributes of an object Possible Complex mutators might: Input an object, alter the real or imaginary parts of an object, set object to zero Facilitators: To use an object to perform an action Possible Complex mutators might: Do complex arithmetic, output object to monitor
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.