Docsity

Understanding Copy Constructors & Assignment Operators in C++, Slides of Object Oriented Programming

Partial preview of the text

Download Understanding Copy Constructors & Assignment Operators in C++ and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 24

Example

class Person{

char * name;

public:

Person(char * = NULL); const char * GetName() const; ~Person();

};

Example

Student::Student(char *_name, char *_maj) : Person(_name), major(NULL)

{

if (_maj != NULL) { major = new char [strlen(_maj)+1]; strcpy(major,_maj); }

}

Example

void Student::Print() const{

cout << “Name: ”<< GetName() <<endl; cout << “Major: “ << major << endl;

}

Example

  • The output is as follows:

Name: Ali Major: Computer Science

Copy Constructor

  • Compiler generates copy constructor for base and derived classes, if needed
  • Derived class Copy constructor is invoked which in turn calls the Copy constructor of the base class
  • The base part is copied first and then the derived part

Example

Person::Person(const Person& rhs){ // Code for deep copy }

int main(){ Student sobj1(“Ali”, “Computer Science”); Student sobj2 = sobj1; sobj2.Print(); return 0; }

Example

  • The output is as follows:

Name: Ali Major: Computer Science

Shallow Copy

...

major

name

sobj

A L I

...

major

name

sobj

C O M ...

A L I

Example

Person::Person(const Person& rhs) { // Code for deep copy } Student::Student (const Student& rhs) { // Code for deep copy }

Copy Constructor

  • The output will be as follows:

Name: Major: Computer Science

  • Name of sobj2 was not copied from sobj

Copy

...

major

name

sobj

A L I

...

major

name

sobj

C O M ...

C O M ...

Copy Constructor

  • The output of previous code will be as follows:

Person Constructor Name: Major: Computer Science

Copy Constructor

  • Programmer must explicitly call the base class copy constructor from the copy constructor of derived class