0% found this document useful (0 votes)
7 views34 pages

Lecture 6 (Copy Constructor)

The document discusses the concept of copy constructors in object-oriented programming, explaining their purpose in initializing objects from existing ones and the default behavior of member-wise copying. It also covers pointers, their operations, and the importance of deep and shallow copying, particularly when dealing with dynamic memory allocation. Additionally, it highlights the need for copy constructors in classes with pointer data members to ensure proper memory management.

Uploaded by

haseebsardar592
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views34 pages

Lecture 6 (Copy Constructor)

The document discusses the concept of copy constructors in object-oriented programming, explaining their purpose in initializing objects from existing ones and the default behavior of member-wise copying. It also covers pointers, their operations, and the importance of deep and shallow copying, particularly when dealing with dynamic memory allocation. Additionally, it highlights the need for copy constructors in classes with pointer data members to ensure proper memory management.

Uploaded by

haseebsardar592
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

EC-201 OOP

LECTURE 5
REFERENCE: ROBERT LAFORE, CHAPTER 6
The Default Copy
Constructor
 Copy constructor is used to initialize an object
with another (existing) object of the same type
(class)
 A default copy constructor is built automatically
into the class if the programmer does not specify
any.
 The default behavior is member-wise copy
Example
int main() {
Distance d1(11, 6.25); //overloaded ctor
Distance d2(d1); //default copy ctor
Distance d3=d1; //default copy ctor
cout<<“\n d1 = “; d1.showDist();
cout<<“\n d2 = “; d2.showDist();
cout<<“\n d3 = “; d3.showDist();
return 0;
}
Returning objects
from functions
class Distance {
int feet; float inches;
public:
Distance(): feet(0), inches(0.0) {}
Distance(int ft, float in): feet(ft), inches(in) {}
void setDist() {
cout<<“\nEnter feet: “; cin>>feet;
cout<<“Enter inches: “; cin>>inches;}
void showDist() { cout<<feet<<“\’-”<<inches<<‘\”’;}

Distance addDist(Distance);
};
Returning objects
from functions
Distance Distance::addDist(Distance d2)
{
Distance temp;
temp.inches=inches + d2.inches;
if (temp.inches>=12.0)
{
temp.inches -= 12;
temp.feet=1;
}
temp.feet += feet + d2.feet;
return temp;
}
void main()
{
Distance d1, d3;
Distance d2(11, 6.25);
d1.getDist();
d3=d1.add(d2);
d1.showDist();
d2.showDist(); d3.showDist();
}
Pointers

 A pointer is a variable whose value is the address of


another variable.
 Like any variable or constant, you must declare a pointer
before you can work with it.
type *var-name;
Using Pointers

There are few important operations


1. Define a pointer variables
2. Assign the address of a variable to a pointer
3. Access the value at the address available in the pointer
variable.
Contd.

Defining a Pointer Variable


int *iptr;
iptr can hold the address of an int

Pointer Variables Assignment:


int num = 25;
iptr = &num;
Contd.

To access num using iptr and indirection


operator *
cout << iptr; // prints 0x4a00
cout << *itptr; // prints 25
Manipulating Data with
Pointers
Value of memory location towards which pointer is
pointing can be changed using pointers
*ptr_nam=val;
For example *iptr=8;
Example 1
void main
{
int * ptr, *foo, *h;
int val=9;
ptr=&val;
foo=ptr;
*foo=10;
int z=*ptr;
cout << val<<“ “<<z;
}
?? What will be the output?
10 10
Example 2

void main
{
int *p;
int val=9;
p=val;
cout<<p;
}
?? Error in the code?
Example 3
void main{
int a = 5, b = 10;
int *p1, *p2;
p1 = &a;
p2 = &b;
*p1 = 10;
p1 = p2;
*p1 = 20;
cout<<a<<“ “<<b;}
?? What will be the output?
10 20
Pointer Arithmetic
 Some mathematical operations may be
performed on pointers.

 The ++ and −− operators may be used to


increment or decrement a pointer variable.
 An integer may be added to or subtracted from
a pointer variable. This may be performed with
the + and − operators, or the += and −=
operators.
 A pointer may be subtracted from another
pointer.
Pointer arithmetic

 There are four arithmetic operators that can be


used on pointers: ++, --, +, and –
 Ptr++ (move one address forward)
 Ptr - - (move one address backward)
 Ptr+i (move i locations forward)
 Ptr-i (move i locations backward)
CLASS EXERCISE
Comparing Pointers
 If one address comes before another
address in memory, the first address is
considered “less than” the second. C++’s
relational operators may be used to
compare pointer values.
Pointers may be compared by using any of C+
+’s relational operators:
> < == != >= <=
example
Initializing pointer to
0
It is always a good practice to assign the pointer
NULL to a pointer variable in case you do not have
exact address to be assigned.

void main ()
{
int *ptr = NULL;
}
Contd.

 If all unused pointers are given the null value you can avoid
the accidental misuse of an uninitialized pointer.
 Many times, uninitialized variables hold some junk values
and it becomes difficult to debug the program.
if(ptr){ // succeeds if p is not null }
if(!ptr) {// succeeds if p is null}
Pointer Rules
Summary
A pointer stores a reference to its pointee. The pointee, in
turn, stores something useful.
The dereference operation on a pointer accesses its pointee.
A pointer may only be dereferenced after it has been assigned
to refer to a pointee. Most pointer bugs involve violating this
one rule.
Allocating a pointer does not automatically assign it to refer
to a pointee. Assigning the pointer to refer to a specific
pointee is a separate operation which is easy to forget.
Assignment between two pointers makes them refer to the
same pointee which introduces sharing.
Shallow and deep copy

void main()
{
int a=9;
int b=a;
a=10;
cout<<a<<b;
}
?? Does change in value of a leads to
change in value of b
Class MyData Void main()
{ {
int *a;
MyData obj1;
public: int j=9;
MyData():a(NULL) obj1.setValue(j);
{ } cout<<obj1.getValue();
MyData obj2=obj1;
MyData(int r) cout<<obj2.getValue();
{ a=new int; *a=r;} obj2.setValue(20);
cout<<obj1.getValue();
void setValue(int m)
{a=new int; *a=m;}
}
int getValue()
{return *a;} Output?

MyData(const Data & t)


{ a=t.a;}
};
COPYING POINTER

void main()
{
int a=9;
int*p =&a;
int*r=p;
*r=6;
cout<<a;
}
COPYING POINTER

void main()
{
int*p=new int;
int *r;
*p=8;
r=p;
*p=9;
cout<<*p<<*r;
}
Deep Copy

void main()
{
int*p=new int;
int *r=new int;
*p=8;
*r=*p;
*p=10;
}
Copy Constructor

The copy constructor is a constructor


which creates an object by initializing it
with an object of the same class, which
has been created previously. The copy
constructor is used to:
 Initialize one object from another of the
same type.
 Copy an object to pass it as an argument
to a function.
 Copy an object to return it from a
function.
Contd.

If the class has pointer variables


and has some dynamic memory
allocations, then it is a must to have
a copy constructor
If a copy constructor is not defined
in a class, the compiler itself defines
one
Syntax: classname(const
classname& obj)
Pointer Class Copy
Constructor
Class PointerInt{ int *ptr;
public:
PointerInt():ptr(NULL){}
PointerInt(int val):ptr(new int),*ptr(val){}
void allocMem(int val) {…..} ;
int addval(PointerInt p){return *ptr+*(p.ptr)}
~PointerInt(){delete ptr; ptr=NULL;}
PointerInt(const PointerInt& b){
ptr=new int;
*ptr=*(b.ptr);
};
Copy Constructor

 Deep Copying
 Called whenever
 an object is created by initializing it with already
existing object of same class
 An object is passed as an argument to a function
 An object is returned from a function
 Class_name(class_name & obj)
Deep copy vs shallow
copy
Shallow Copy Deep Copy
Void main() Void main()
{ {
int *p,*q; int *p,*q;
p=new int; p=new int;
*p=5; *p=5;
q=p; // shallow copy q=new int;
*q=9; *q=*p; // deep copy
cout<<*p; cout<<*p;
} }
CLASSES WITH POINTER
DATA MEMBER
 Constructor to ensure Memory is
allocated
 Setter to ensure Value initialized
to memory
 Destructor to ensure de allocation
 Copy constructor should be
provided to ensure deep copy

Why?
Reading Assignment

 Robert Lafore, 4th edition, pages 247-249

You might also like