Docsity

Object Oriented Programming Lecture 9: Copy Constructors and Destructors, Slides of Object Oriented Programming

Partial preview of the text

Download Object Oriented Programming Lecture 9: Copy Constructors and Destructors and more Slides Object Oriented Programming in PDF only on Docsity!

Object Oriented Programming

(OOP)

Lecture No. 9

Review

Member functions implementation

Constructors

Constructors overloading

Copy constructors

Example

void

func1(Student

student){

… } int

main(){

Student

studentA(“Ahmad”);

Student

studentB

=

studentA;

func1(studentA);

Copy Constructor (contd.)

Student::Student(

const

Student

&obj){

rollNo

=

obj.rollNo;

name

=

obj.name;

GPA

=

obj.GPA;

}

Example

Student studentA(“Ahmad”);

studentB RollNnName GPA

Heap

A H M A D

studentA RollNnName GPA

Student studentB = studentA;

Example

int main(){

Student studentA(“Ahmad”,1); {

Student studentB = studentA;

studentB RollNnName GPA

Heap

A H M A D

studentA RollNnName GPA

Copy Constructor (contd.)

Student::Student(

const Student & obj){

int len = strlen(obj.name);name = new char[len+1]strcpy(name, obj.name);… /copy rest of the data members/

}

Example

int main(){

Student studentA(“Ahmad”,1); {

Student studentB = studentA;

A H M A D

studentA RollNnName GPA

studentB RollNnName GPA

A H M A D

Copy Constructor (contd.)

Copy constructor is normally used to perform deep copy

If we do not make a copy constructor then the compilerperforms shallow copy

Destructor

Destructor is used to free memory that is allocated through dynamicallocation

Destructor is used to perform house keeping operations

Example

class

Student

public:

~Student(){

if(name){

delete

[]name;

Overloading

►

Destructors cannot be

overloaded

Example

Student::Student(char

aName){

cout

aName

“Cons\n”;

} Student::~Student(){

cout

name

“Dest\n”;

Example

int

main()

{

Student

studentB(“Ali”);

Student

studentA(“Ahmad”);

return

0;

}