Docsity

Understanding Shallow and Deep Copy in C++ with Student Class, Slides of Object Oriented Programming

Partial preview of the text

Download Understanding Shallow and Deep Copy in C++ with Student Class and more Slides Object Oriented Programming in PDF only on Docsity!

ObjectObject--Oriented ProgrammingOriented Programming

(OOP)(OOP)

Lecture No. 24 Lecture No. 24

ExampleExample

class Student: public Person{ class Student: public Person{

char* major; char* major;

public: public:

Student(char *, char *); Student(char *, char *); void Print() const; void Print() const; ~Student(); ~Student();

}; };

ExampleExample

► ► The output is as follows:The output is as follows:

Name: Ali Name: Ali Major: Computer Science Major: Computer Science

Shallow CopyShallow Copy

......

majormajor

namename

sobj2sobj

A

L

I

......

majormajor

namename

sobj1sobj

C

O

M

Shallow CopyShallow Copy

......

majormajor

namename

sobj2sobj

A

L

I

......

majormajor

namename

sobj1sobj

C

O

M

A

L

I

ExampleExample

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

Copy ConstructorCopy Constructor

► ► The output of previous code will be asThe output of previous code will be as follows: follows:

Person Constructor Person Constructor Name: Name: Major: Computer Science Major: Computer Science

ExampleExample

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

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

ExampleExample

int main() int main()

{ {

Student sobj1, sboj2( Student sobj1, sboj2(““AliAli””,, (^) ““CSCS””);); sobj1 = sobj2; sobj1 = sobj2; return 0; return 0;

} }

Assignment OperatorAssignment Operator

► ► Programmer has to call operator of baseProgrammer has to call operator of base class, if he is writing class, if he is writing assignment operatorassignment operator of derived class of derived class

ExampleExample

► ► The assignment operator of base class isThe assignment operator of base class is not called not called

► ► OutputOutput

Student Assignment Student Assignment

Calling Base Class Member FunctionCalling Base Class Member Function

► ► Base class functions can be explicitly called with referenceBase class functions can be explicitly called with reference to base class itself to base class itself

//const char* Person::GetName() {...}; //const char* Person::GetName() {...}; void Student::Print() void Student::Print() { { cout << GetName(); cout << GetName(); cout << Person::GetName(); cout << Person::GetName(); } }