Docsity

Member Functions Implementation - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Member Functions Implementation - Object Oriented Programming - Lecture Slides 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”);

GPA

Name

RollNn

studentB

Heap

A H M A D

GPA

Name

RollNn

studentA

Student studentB = studentA;

Example

int main(){ Student studentA(“Ahmad”,1); { Student studentB = studentA;

GPA

Name

RollNn

studentB

Heap

A H M A D

GPA

Name

RollNn

studentA

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

GPA

Name

RollNn

studentA

GPA

Name

RollNn

studentB

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 compiler

performs shallow copy

Destructor

• Destructor is used to free memory

that is allocated through dynamic

allocation

• 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;