DOC PREVIEW
Saddleback CS 1C - Topic 10 - Copy Constructors

This preview shows page 1-2 out of 5 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS1C – Advanced Programming in C++Saddleback College Fall 2011 – J TateyamaTopic 10 - Copy ConstructorsChapter 7 in ShrinkwrapCS1C – Saddleback CollegeCopy ConstructorsReminder – Only 2 built in C++ operations on classes–member access operator (.)–assignment (=) Copy Constructor provides means of creating a new object by using the value of an existing objectDefault copy constructor is supplied by the compiler but results in a “shallow copy” of the data – contents of data members are copied to the new object. Also called member-wise initialization.If one of the data members is a pointer then both objects will contain the same address which can result in unpredictable resultsCS1C – Saddleback CollegeCopy Constructor Examplestruct IntNode{int val;IntNode* next;};class LinkedListClass{public:LinkedListClass( );~LinkedListClass( );void BuildList( ); //add nodes to listvoid DestroyList( ); //walk list and destroy nodesvoid PrintList( ) const; //output contents of listprivate:int listLen;IntNode* head;};CS1C – Saddleback CollegeCopy Constructor ExampleGiven LinkedListClass obj1;After obj1.BuildList()After LinkedListClass obj2 = obj1;or LinkedListClass obj2(obj1);–obj2 is instantiated using the values of obj1–default copy constructor supplied by compiler is called resulting in shallow copy of data members–data member contents of obj1 are copied into data members of obj2–so obj2.head gets a copy of the address contained in obj1.headobj10• listLenhead3 7 3• 3 listLenheadobj23 listLenheadCS1C – Saddleback CollegeCopy Constructor ExampleAfter obj2.DestroyList();Now left with dangling pointer in the pointer field of obj1What is needed is to provide an override to the default copy constructor provided by the compiler for this classWhat to add to class?LinkedListClass(const LinkedListClass& anotherObj );obj13 lstLenhead0• lstLenheadobj2CS1C – Saddleback CollegeCopy Constructor ExecutionWhen is Copy Constructor executed?–Called when an object is declared and initialized by using the value of another object–When an object is passed as a value parameter •Note: whenever you pass an object by value as an argument to a function, the compiler will make a copy of the object by calling the copy constructor–When an object is to be returned from a functionCS1C – Saddleback CollegeDifferent Types of Initialization – Direct and CopyDirect initialization–Calls the constructor when object is instantiatedCopy initialization–Calls the constructor to create a temporary object then the temporary object is copied into the object being created–Can only be used on class objects when specifying a single argument or when explicitly building a temporary object to copyCS1C – Saddleback CollegeInitialization – Direct and Copy Exampleclass Cls{public:Cls();Cls(int n);int GetVal()const;private:int val;};//declarations in the main Cls obj1; // direct initializationCls obj2(5); // direct initializationCls obj3 = 7; // copy initializationstring strVal("Hello World"); // direct initializationstring strVal2 = string( ); // copy initializationCS1C – Saddleback CollegeReview of some cstring Functions (string.h)strcpy –This function receives the addresses of two strings and copies the second string to the first string. –The arguments may be char pointers, the names of arrays or a combination of the two. –Recall that it is up to the programmer to check that the second string is not larger than the first. If it is, the function will simply overwrite memory beyond the size of the first string. strlen–This function receives the address of a string and returns the length of the string. Number of characters from the beginning of the string and the null terminator.–The null terminator is not included as part of the length. –The argument may be a char pointer, the name of a char array, or a string literal.–should not be confused with the size of the array that holds the string CS1C – Saddleback Collegecstring Function Exampleclass Person{public:Person();Person(char* nm, int age); //char* nm – pointer variable~Person();char* GetName()const; //returns pointer variableint GetAge()const;void SetData(char* nm, int age);private:char* pName;int pAge;};void main(void){Person p1("Sam Jones",25);cout << "\n\n" << p1.GetName() << ' ' << p1.GetAge();Person p2 = p1;cout << "\n\n" << p2.GetName() << ' ' << p2.GetAge();p2.SetData("Sally Smith",45);cout << "\n\n" << p1.GetName() << ' ' << p1.GetAge();cout << "\n\n" << p2.GetName() << ' ' << p2.GetAge();}CS1C – Saddleback Collegecstring Function Example ContinuedPerson::Person() : pName(" "),pAge(0) {} //default constructor with initializer listPerson::Person(char* nm, int age){//first create a dynamic array large enough to hold the string literal & null terminatorpName = new char[strlen(nm) + 1];//then copy the literal value into the c-stringstrcpy(pName, nm);page = age;}Person::~Person(){}char* Person::GetName()const{return pName;}int Person::GetAge()const{return pAge;}CS1C – Saddleback Collegecstring Function Example Continuedvoid Person::SetData(char* nm, int age){strcpy(pName,nm);pAge = age;}What is output of this example?–Sam Jones 25–Sam Jones 25–Sally Smith 25–Sally Smith 25Why?–one of the members of the class is a pointer–p2 was instantiated not by a call to the constructor but from the p1 object–therefore memberwise assignment took place; –p2’s pName got the address of pName in p1CS1C – Saddleback CollegeCopy Constructor DefinitionA special constructor that is called whenever a new object is created and initialized with data from another object. It has the same basic form as other constructors but it has one and only one reference parameter of the same type as the object itself.General format:className(const className& parameterObj);CS1C – Saddleback CollegeCopy Constructor Implementation// copy constructor declarationPerson::Person(const Person& obj);// copy constructor implementationPerson::Person(const Person& obj){// create a char array large enough to hold the string and the null terminatorpName = new char[strlen(obj.pName) + 1;// make a copy of the name and place it in the newly created arraystrcpy(pName,obj.pName);pAge = obj.pAge;}The statementPerson p2 = p1;causes the copy constructor of p2 to be called and parameter obj receives the address of p1.NOTE: If the object, obj, is passed by value the default


View Full Document
Download Topic 10 - Copy Constructors
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Topic 10 - Copy Constructors and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Topic 10 - Copy Constructors 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?