Constructors and Other Tools Version 1.0 Topics Constructors & Destructors Composition const Parameter Modifier const objects const functions In-line.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Advertisements

Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Chapter 7: User-Defined Functions II
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Chapter 14: Overloading and Templates
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Classes: A Deeper Look Systems Programming.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 11: Classes and Data Abstraction
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Learners Support Publications Classes and Objects.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
CONSTRUCTORS AND DESTRUCTORS Chapter 5 By Mrs. Suman Verma PGT (Comp.Sc)
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
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:
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 11: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
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.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Learners Support Publications Constructors and Destructors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Constructors and Destructors
Classes and Objects.
Static data members Constructors and Destructors
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
More on Classes Classes may have constructors which are called when objects are created and destructors which are called when objects are destroyed. Classes.
Introduction to Classes
Constructors and Other Tools
Constructors and Destructors
Classes and Objects.
Presentation transcript:

Constructors and Other Tools Version 1.0

Topics Constructors & Destructors Composition const Parameter Modifier const objects const functions In-line functions Static data and member functions

Objectives After completing this topic, students should be able to: Correctly write and use constructors in a program Use an initializer list in a constructor Describe the use of the default constructor Understand and use composition relationships in programs Correctly use the const modifier Know what static data is and correctly use static data in a program Know what a static function is and correctly use a static function in a program

Constructors Creating objects with un-initialized member data can be dangerous. If that member data is used somewhere later in the program, it will be garbage. Constructors provide us with a handy way to initialize member data when an object is created.

Important Note: Constructors don’t create objects! They are used to initialize data in an object.

Constructor Definitions A constructor is a member function of a class, but it has two unique qualities: * It must have the same name as the class * It has no return type ( not even void)

class CoinBank { private: double moneyInBank; public: CoinBank ( ); double howMuchMoney ( ); void addMoney (double); void takeMoney (double); }; This is the default constructor for the CoinBank class. Notice that it has the same name as the class and has no return type and no parameters.

CoinBank::CoinBank( ) { moneyInBank = 0; } The implementation of the CoinBank default constructor looks like this. Like any member function, we use the class name and the scope resolution operator when writing the implementation. This is the code to be executed when the constructor is called. In this case we initialize the money in the bank to zero.

CoinBank::CoinBank (double n) : moneyInBank(0.0) { if (n >0.0) moneyInBank = n; } A slightly more complicated constructor might take a parameter and use the parameter to set the initial value. By overloading the constructor we can provide both definitions.

Using the Constructor The constructor is called when an object is declared. CoinBank myBank; CoinBank billsBank (5.00); This declaration calls the default (non-parameterized) constructor. Notice that there are no parentheses used when invoking the default constructor. This declaration calls the parameterized constructor, passing in the value of 5.00.

Using an Initializer List CoinBank::CoinBank (double n) : moneyInBank (n) { } The initializer list initializes the data members. This technique is preferred because initialization occurs as memory is being allocated for the data members. The initializer list goes between the parameter list and the opening brace for the function. Each element of the list is made up of the data member name followed by the value, in parentheses, to be assigned to that data member.

CoinBank::CoinBank (double n) : moneyInBank (n) { if (moneyInBank < 0) moneyInBank = 0.0; } You can add error checking or other code inside the body of the constructor.

Default Constructor By default constructor, we mean a constructor that takes no parameters. When a class is defined, the compiler automatically creates a non-parameterized constructor. This constructor does no initialization. If you write a parameterized constructor in your class definition, the compiler then does not create a default constructor. If you want one, you must write it yourself.

Explicit Constructor Calls Normally a constructor is only used when declaring an object. However, we can make an explicit constructor call to re-initialize the data members of an object as follows: myPiggyBank = CoinBank ( ); The right hand side of this expression creates an anonymous (nameless) object and then calls the constructor to initialize its data members. The assignment statement then copies the values of the anonymous objects data members into myPiggyBank’s data members. The anonymous object is then destroyed. Note that in this case you must include the parentheses when using the default constructor.

Destructors Destructors are member functions of a class, with the following differences: * It has the same name as the name of the class * It is preceded by a ~ * It cannot have any parameters CoinBank::~CoinBank() { //function body used to clean up after the object! }

Using the Destructor The destructor is called when an object is destroyed. CoinBank myBank; } This declaration calls the destructor when the object goes out of scope “}”.

Composition A class may have a data member that is itself an object of another class. This unique class relationship is called composition.

Composition Example The Soda Machine

Vending Unit Change Unit Soda Machine $

VendingUnit - someCans : int +VendingUnit ( :int ) +VendingUnit ( ) +giveOne( ): bool

ChangeUnit - change: int + ChangeUnit ( ) +ChangeUnit ( :int ) + void giveIt ( :int ) $$$$

Soda Machine + selection : int - changer : ChangeUnit - vendor : VendingUnit + SodaMachine ( int, int ) + ~SodaMachine() + run ( ) : int - buy ( ) : void

Vending Unit Change Unit Soda Machine user Main { … } run Select = 1 menu buy giveOne giveIt Functions User I/F $$$$

SodaMachine sodaMachine ChangeUnit changer VendingUnit vendor main run selection menu buy deposit $ inMoney giveOne giveIt ( inMoney ) A Sequence Diagram

int SodaMachine::run ( ) { while ( true ) { cout << “\n\n\nRoger’s Soda Machine\n”; cout << “MENU (Type a number and hit ENTER:\n”; cout << “1 – buy a soda\n”; cout << “2 – stop simulation\n”; cin >> selection; if ( selection == 1 ) buy ( ); else if ( selection == 2 ) break; else cout << “Invalid selection …\n”; } return 1; }

void SodaMachine::buy ( ) { int inMoney; bool okay; while ( true ) { cout << “Soda’s cost 25 cents\n”; cout << “How many cents are you putting in?\n:”; cin >> inMoney; if ( inMoney >= 25 ) break; cout << “Not enough … try again.\n”; } okay = vendor.giveOne ( ); if ( okay ) changer.giveIt ( inMoney ); }

Principle of Least Privilege A function should have the least possible access to data required to do its job.

The const Parameter Modifier Call by reference is more efficient than call by value. When using call by reference, and you know that a function should not change the value of a parameter, mark the parameter so that the compiler knows it should not be changed. Reduces “coupling” to the variable! bool isLarger (const BankAccount& acct1, const BankAccount& acct2);

Rules for Function Parameters 1. For basic data type parameters, e.g., int, float, etc, pass the parameters by value 2. For non-basic data type parameters, e.g. arrays, objects and structs, pass the parameters by reference. 3. When passing by reference, if the function should not change the value of the parameter, use the const modifier.

Constant Objects You can use the const modifier when declaring an object, to make all of the data members of the object constant. Note that constantness is a property of an object, not a class!

Example Consider a Time class whose data members are hours, minutes, and seconds. You might declare a Time Object to keep track of the wake up time for an alarm clock. Since you may change the time you wake up each day, the Time object would not be declared as constant. However, if you wanted a Time object to represent the time of 12 noon, then you would make the object constant, since the time at which noon occurs never changes. const Time noon (12, 0, 0);

const Functions Most C++ compilers will not allow member functions for const objects unless the functions themselves are declared as const. Member functions declared as const cannot modify the object. A function is declared as const both in its prototype and in the function implementation. void Time::displayTime( ) const { … } the const keyword follows the function’s parameter list.

In-Line Functions You can give the complete implementation of a function within the definition of its class. class PiggyBank { public: PiggyBank( ); double getMoneyInBank( ) const { return moneyInBank; } … };

When the implementation of a function is written in-line in the class definition, the compiler treats the code differently. Under normal circumstances, whenever a function is invoked, the compiler generates a call to the function code, which is written into memory just once. When a function is in-line, the compiler inserts the machine code for the function everyplace that the function is called. Putting a function inline does not guarantee that inline code will be generated!

int getStuff ( ) { return stuff; } Normal Function call machine code for getStuff … compiler main ( ) { getStuff( ); … getStuff( ); … getStuff( ); } save environment put parameters on the stack pass control to function get return value off of stack restore environment compiler save environment put parameters on the stack pass control to function get return value off of stack restore environment compiler save environment put parameters on the stack pass control to function get return value off of stack restore environment compiler

machine code for getStuff( ) machine code for main( ) getStuff( ) memory save environment put parameters on the stack pass control to function get return value off of stack restore environment

In-Line Function Call int getStuff ( ) { return stuff; } machine code for getStuff … compiler main ( ) { getStuff( ); … getStuff( ); … getStuff( ); } compiler machine code for getStuff( ) compiler machine code for getStuff( ) compiler machine code for getStuff( )

machine code for main( ) memory machine code for getStuff( ) machine code for getStuff( ) machine code for getStuff( ) in-Line functions eliminate the overhead of calling a function but … the executable code takes more space in memory because the code for the function is repeated over and over again.

Static Data Members Normally, each object of a class keeps its own copy of the data members defined in the class. class PiggyBank { private: int moneyInBank; … } PiggyBank myBank; moneyInBank $3.50 PiggyBank yourBank; moneyInBank $17.25 PiggyBank bigBank; moneyInBank $

When a data member is declared as static, only one copy is created, nor matter how many objects are created. All objects share this single copy of the data member. class PiggyBank { private: float moneyInBank; static float interestRate; … } PiggyBank myBank; moneyInBank $3.50 moneyInBank $17.25 PiggyBank bigBank; moneyInBank $ interestRate.0525 PiggyBank yourBank;

Initializing Static Data Members Static data members are initialized outside of the class definition, but typically in the same file as the class definition. Static data members can only be initialized once. float PiggyBank::interestRate =.0525; This initialization works even if the data is declared private.

Static Member Functions Member functions of a class can also be declared as static. A static member function can be invoked without an object of the class ever having been created. As a result, static member functions cannot do anything that depends on there being a calling object. In particular, a static function cannot use non-static member data. Static member functions are usually invoked using the class name: PiggyBank::setRate (0.325);

class Dumb { private: static int number; public: static getNumber( ); }; Dumb::getNumber( ) { return number; } int Dumb::number = 5; int main( ) { cout << Dumb::getNumber( ); cin.get( ); return 0; } Static Function!

Practice Consider the Integer class we examined in the last set of slides.

Design a class that represents “Integer” objects. Suppose we want functions to set the integer value in the object retrieve the integer value in the object retrieve the reciprocal of the value in the object

Write a non-parameterized constructor. What should the default value of an Integer be?

Write a parameterized constructor. Write it with and without an initializer list.

Define the class such that one if its data members keeps track of how many Integer objects have been created.

An Engine Object A Drive Train Object A Wheel Object Here is an Example of Composition

What other real world objects could we model using composition relationships?

What are the benefits of an in-line function? What are the problems with in-line functions?