Dynamic Memory for Class #include #ifndef STRCLASS_H_ #define STRCLASS_H_ class strclass { private: char *str; int len; static int num_strings; public:

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Operator overloading redefine the operations of operators
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.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Introduction to Programming Lecture 39. Copy Constructor.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Memory Management Object Life Cycle:  Construction  Allocation  Preinitialization  Initialization  Use  Destruction  Cleanup  Post cleanup  Deallocation.
Reusing Code Private or Protected inheritance. A cool class for array valarray class deals with numeric values, and it supports operation such as summing.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Operator Overloading CS 308 – Data Structures What is operator overloading? Changing the definition of an operator so it can be applied on the objects.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
C++ Review (3) Structs, Classes, Data Abstraction.
Copy Constructors Fall 2008 Dr. David A. Gaitros
1 CSC241: Object Oriented Programming Lecture No 22.
J. P. Cohoon and J. W. Davidson © 1997 McGraw-Hill, Inc. Templates Generic functions and classes.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
More C++ Features True object initialisation
UFS003C3 Lecture 15 Data type in C & C++ Using the STL.
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.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
1 Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 10 More on Objects and Classes.
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 Memory as byte array Pointers Arrays relationship to pointers Operator ‘new’ Operator ‘delete’ Copy ctor Assignment operator ‘this’ const pointer Allocating.
CSIS 123A Lecture 10 Inheritance. Organizing Code Why should programs be organized? –Humans are "complexity challenged" Need simplicity, clarity, efficiency.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 CS 132 Spring 2008 Chapter 5 Linked Lists p
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Chapter 2 Objects and Classes
Yan Shi CS/SE 2630 Lecture Notes
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Strings: C-strings vs. Strings as Objects
CS1220 Midterm Review.
Overloading Operator MySting Example
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.
Constructor & Destructor
14.4 Copy Constructors.
Class: Special Topics Copy Constructors Static members Friends this
LinkedList Class.
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 2 Objects and Classes
group work #hifiTeam
Automatics, Copy Constructor, and Assignment Operator
Automatics, Copy Constructor, and Assignment Operator
Strings: C-strings vs. Strings as Objects
Copy Assignment CSCE 121 J. Michael Moore.
Summary: Abstract Data Type
Constructors and Destructors
COP 3330 Object-oriented Programming in C++
Copy Assignment CSCE 121.
Destructors, Copy Constructors & Copy Assignment Operators
Destructors, Copy Constructors & Copy Assignment Operators
C++ support for Object-Oriented Programming
Presentation transcript:

Dynamic Memory for Class #include #ifndef STRCLASS_H_ #define STRCLASS_H_ class strclass { private: char *str; int len; static int num_strings; public: strclass(const char *s); strclass(); ~strclass(); friend ostream & operator << (ostream &os, const strclass &st); } ; #endif;

A static class member is created for all objects ( it is share); #include #include “strclass.h”; int strclass :: num_strings=0; strclass::strclass(const char *s) { len=strlen(s); str=new char[len+1]; strcpy(str,s); num_strings++; cout<<num_strings<<“: “<<str<<endl; }

strclass::strclass() { len=4; str=new char[4]; strcpy(str,”C++”); num_strings++; cout<<num_strings<<“: “<<str<<endl; } strclass::~strclass() { cout<<str<< “ object deleted ”; --num_strings; cout<<num_strings<< “ left \n”; delete [ ]str; }

ostream & operator<<(ostream &os,const strclass & st) { os<<st.str; return os; } We can’t initialize static member inside class declaration.

#include #include “strclass.h”; void call1( strclass & rsb) { cout<<“pass by reference \n”; cout<<rsb<<“\n”; } void call2( strclass sb) { cout<<“pass by value \n”; cout<<sb<<“\n”; }

int main() { strclass headline1(“this is test1”); strclass headline2(“this is test2); strclass sport(“A won B”); cout<<headline1<<endl; cout<<headline2<<endl; cout<<sport<<endl;

call1(headline1); cout<<headline1<<endl; call2(headline2); cout<<headline2<<endl; strclass sailor=sport; cout<<sailor<<endl; strclass headline3= headline1; cout<<headline3<<endl; return 0; }

after calling call2(headline2) we see some junk character; At the end of main we see : This is test1 object deleted, 2 left; This is test2 object deleted, 1 left; This is testBV object deleted, 0 object deleted, -1 left; -| object deleted, -2 left;

It gets messy! C++ automatically provides member functions : default constructor if you don’t define one copy constructor if you don’t define one assignment operator if you don’t define one default destructor if you don’t define one Address operator if you don’t define one

copy constructors is used when we explicitly initialize an object to another one. It copies all non-static member one by one (deep copying) In the previous example when we call call2(); the default copy constructors called so it doesn’t increase the num_strings. When we assign sport to sailor then we have sailor.str=sport.str; But actually the pointers point to the same string By deleting one the other one is deleted.

Solution: Fixing the problem with explicit copy constructor (deep copy) strclass::strclass(const strclass & st) { num_strings++; len=st.len; //same length; str=new char[len+1]; strcpy(str,st.str); cout<<num_strings<<“: “<<str<<endl; cout<<“ object created \n”; }

Assignment operators The syntax is : class_name & class_name::operator=(const class_name &) { }

When we use Assignment operators assigning one object to existing object. strclass headline3; headline3=headline1; // = operator invoked. It copies member-to-member. But actually the pointers point to the same string hedline3.str=headline1.str;

Solution strclass & strclass:: operator=(const strclass & st) { if(this== & st) return *this; delete [ ] str; len=st.len; str=new char[len+1]; strcpy(str,st.str); return *this; }

Things to remember when using new in Constructors After using new to initialize a pointer, we should use delete in destructor. new and delete should be compatible. new with delete and new [ ] with delete [ ]. If there are multiple constructors, all should use new the same way, either all with [ ] or without [ ].

We should use a copy constructor that initialize one object to another by doing deep copying. We should define an assignment operator that copies to another by doing deep copying.

Static Class Member Function We can declare a member function as being static. A static member function doesn’t have to be invoked by an object. A static member function can use only static data member.