The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
CSE 332: C++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Winter 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assn 4 posted shortly. Demonstrate a memory leak problem using the assignment 4 solution. Back to.
Class and Objects.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Classes Separating interface from implementation
Classes: A Deeper Look Systems Programming.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
CS-2303 System Programming Concepts
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.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Pointer Data Type and Pointer Variables
CS352-Week 2. Topics Heap allocation References Pointers.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
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.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
More C++ Features True object initialisation
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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:
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
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.
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.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Yan Shi CS/SE 2630 Lecture Notes
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.
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 7 CS 3370 chapter 7 CS 3370 – C++ Classes.
CS410 – Software Engineering Lecture #11: C++ Basics IV
Class: Special Topics Copy Constructors Static members Friends this
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
CS212: Object Oriented Analysis and Design
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Constructors and Destructors
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
9-10 Classes: A Deeper Look.
C++ Constructor Insanity CSE 333 Summer 2018
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

The Rest of the Story

 Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment Operator 2 CS C++ Software Development

 Execute after an object’s memory is allocated  Used to initialize an object’s memory  Which constructor executes depends on arguments passed  Run after sub-objects are initialized  Base classes and sub-objects initialize first  Example: initMembers.cpp 3 CS C++ Software Development

 Member objects are default-initialized  class types run the default constructor  built-in types are not initialized by default  See initInt.cpp, defaultinit.cpp  “Zero Initialization”:  Occurs with an explicit call to a default ctor  Even with built-ins: int x = int( ); // 0  See defaultinit2.cpp CS C++ Software Development 4

 By-passes default initialization  The only way to initialize const and reference members  It is inefficient and poor practice to initialize member objects in the body of the containing constructor  Built-in types are okay, though  Examples: badInit.cpp, goodInit.cpp, constMem.cpp 5 CS C++ Software Development

#include class String { char* data; public: String(const char* s = "") { data = new char[std::strlen(s) + 1]; std::strcpy(data,s); } ~String() {delete [] data;} int size() const {return std::strlen(data);} char getAt(int pos) const {return data[pos];} void setAt(int pos, char c) const {data[pos] = c;} void display() { std::cout << data << '\n'; } }; 6 CS C++ Software Development

int main() { String s = "hello"; // same as String s("hello"); for (int i = 0; i < s.size(); ++i) cout << "s[" << i << "] == " << s.getAt(i) << std::endl; String empty; std::cout << '"'; empty.display(); std::cout << "\"\n"; } /* Output: s[0] == h s[1] == e s[2] == l s[3] == l s[4] == o "" */ 7 CS C++ Software Development

int main() { String s = "hello"; String t = s;// same as String t(s); t.setAt(0,'j'); s.display(); } /* Output: jello a.out(4603) malloc: *** error for object 0x : pointer being freed was not allocated */ 8 CS C++ Software Development

 Initialization occurs only once, right after an object is created ▪ always by some constructor  Assignment occurs only after an object has been initialized ▪ via operator=  Which constructor executed in the previous slide? 9 CS C++ Software Development

 Initializes a new object as a copy of an existing object  of the same type or of some convertible type  Has signature T::T(const T&)  or T::T(T&)// not recommended  Copies each member across  using their own copy constructors, recursively  Generated by the compiler  But you can override it (and sometimes should) 10 CS C++ Software Development

String(const String& s) : data(s.data) {} // Identical here to: String(const String& s) { data = s.data; } (because pointers are not objects, and hence are not default-initialized.) 11 CS C++ Software Development

hello\0 s::data t::data 12 CS C++ Software Development

 If you have a pointer as a data member, a shallow copy is probably not what you want  Multiple pointers point to the same memory  If you de-allocate the data member in one object, you have created a likely fatal situation in the other (double delete) 13 CS C++ Software Development

 Classes with pointer members representing a dynamically allocated resource should offer a deep copy:  Allocate new heap space  Copy data to new target 14 CS C++ Software Development

String(const String& s) { data = new char[strlen(s.data)+1]; strcpy(data, s.data); } 15 CS C++ Software Development

 Rarely done for non-built-in types  Objects are often returned by value, though  New values are often created  A copy is made  Therefore, a constructor executes  But which constructor? 16 CS C++ Software Development

 Not always the copy constructor  Depends on the argument(s)  via overload resolution  As simple as that!  Example: trace.cpp 17 CS C++ Software Development

 Why does changing t affect s below? int main() { String s = "hello"; // same as String s("hello"); String t; t = s; t.setAt(0, 'j'); s.display(); } /* Output: jello a.out(4767) malloc: *** error for object 0x : pointer being freed was not allocated */ 18 CS C++ Software Development

 Uses operator=  must be a member function  Generated by the compiler  assigns each data member individually  does a shallow copy  You can override it  and sometimes should, just like the copy constructor 19 CS C++ Software Development

String& String::operator=(const String& rhs) { data = rhs.data; return *this; } hello\0 s t 20 CS C++ Software Development

 Allocate new heap space  Copy characters to target   Delete the old heap space   Return *this  Avoid unnecessary self-assignment  An optional but encouraged optimization  And watch the order you do things in! 21 CS C++ Software Development

String& String::operator=(const String& s) { if (&s != this)// avoid self-copy { char* new_data = new char[strlen(s.data)+1]; strcpy(new_data, s.data); // copy delete [] data; // delete old data = new_data; // store new } return *this;// for full ass’t. semantics } 22 CS C++ Software Development

 A must for large objects (streams, etc.)  Make the copy constructor and assignment operator private  Will cause a compile error if client code tries to copy or assign  Only declare them  Define no function bodies  Will cause a link error if member functions try to copy or assign 23 CS C++ Software Development

 Implicit promotion of numeric types  Widening of:  char -> short -> int -> long -> long long  Conversion from integer to floating-point  Needed in mixed-mode expressions (x + i) and in passing parameters  Function prototypes initiate the conversion for parms 24 CS C++ Software Development

 You can allow conversions to and from any class type from or to any other type  Convert to a class type via a single-arg constructor ▪ aka “conversion constructor”  Convert from a class type via a conversion operator ▪ a special type of member function  You can turn off implicit conversions  With a special keyword (explicit) 25 CS C++ Software Development

 Sometimes multiple conversions occur invisibly in sequence in a single expression  Only one class type (i.e., non-primitive) is allowed inside a sequence of conversions  Example  convert.cpp  convert2.cpp 26 CS C++ Software Development

 explicit keyword  Example  convert3.cpp 27 CS C++ Software Development

 Copy Constructor  the compiler generates a shallow one if you don’t define it  All Other Constructors  if you don’t provide any constructors at all, the compiler generates a default constructor (which default-constructs each member)  Single-arg constructors are conversion constructors  Assignment Operator  the compiler generates a shallow one if you don’t define it  Destructor  the compiler generates an empty one if you don’t define it  Members with destructors are destructed automatically anyway 28 CS C++ Software Development

 const is your friend  It prevents modification errors by enforcing "read-only- ness"  const objects can only call const member functions  all objects can call const member functions!  const member functions receive the following this pointer:  const T * const this  Non-const member functions receive the following this pointer:  T * const this CS C++ Software Development 29

 const member functions cannot change fields:  “x = 2”  “this->x = 2”// error in a const fn  Unless they’re mutable  “x = 2”  “const_cast (this)->x = 2”  See mutable.cpp  Remember: const is a user-view thing CS C++ Software Development 30

 Objects don’t exist until they are fully initialized by a constructor  Constructors do not receive a this pointer  This if OK: you have to modify things during initialization!  So you don’t declare constructors const  Nor do they return anything CS C++ Software Development 31

 Consider front, back, and at in class Deque  They are non-const functions  They can’t be applied to a const Deque object  You can overload on const  So you can define overloaded const versions  See deque2.cpp and deque3.cpp  However, there is a problem with the return by reference!  Look at the return types of the const versions CS C++ Software Development 32

 A const member function should never return a non-const reference  Remember, it’s a user-view thing  You are responsible to enforce this!  Always provide two overloads:  T& f( );  const T& f() const;  Classical example: the indexing operator (same as at( ))  T& operator[](int pos);  const T& operator=(int pos) const;  See deque4.cpp CS C++ Software Development 33

 Only the declaration goes in the class definition  Usually in a.h file  The definition of the member must occur at global scope  In a.cpp file  Defines space for the member in the data segment  (There is no “class object” in C++ like in other OO languages) CS C++ Software Development 34

 In MyObject.h: class MyObject { static Pool pool; … };  In MyObject.cpp: Pool MyObject::pool(…); CS C++ Software Development 35