CS 596 OODP
Correction on Copy Constructors
[To Lecture Notes Index]
San Diego State University -- This page last updated Oct. 28, 1995

#include <iostream.h>
class OK {
public:
int size;
OK( int initialSize = 10 );
~OK() { cout << "Kill OK: " << size << endl; };
};
OK :: OK( int initialSize ) {
size = initialSize;
cout << "New OK: " << initialSize << endl;
};
class Trouble {
public:
int Location;
OK test;
Trouble( int StartValue = 5 );
};
Trouble :: Trouble( int StartValue ) {
Location =StartValue ; test.size = 20;
};
void main() {
Trouble NotMe;
Trouble ThisIsFine = NotMe;
};
Output
New OK: 10
Kill OK: 20
Kill OK: 20
#include <iostream.h>
class OK {
public:
int* size;
OK( int initialSize = 10 );
OK( const OK& Copy );
~OK() {delete size; cout << "Kill OK " << *size << endl; };
};
OK :: OK( int initialSize ) {
size = new int( initialSize );
cout << "New OK: " << initialSize << endl; };
OK :: OK( const OK& Copy ) {
size = new int( *(Copy.size) );
cout << "New Copy OK: " << *size << endl; };
class Trouble {
public:
int Location;
OK test;
Trouble( int StartValue = 5 );
};
Trouble :: Trouble( int StartValue ) {
Location =StartValue ; *(test.size) = 20;};
void main() {
Trouble NotYet;
Trouble ThisIsFine = NotYet;};
Output
New OK: 10 Kill OK 20
New Copy OK: 10 Kill OK 20
Copying - Copy Constructor in Copy Constructor
class OK {
public:
int* size;
OK( int initialSize = 10 );
OK( const OK& Copy );
~OK() {delete size; cout << "Kill OK:" << *size << endl; }; };
// See previous page for OK constructors
class Trouble {
public:
int* Location;
OK test;
Trouble( int StartValue = 5 );
Trouble( const Trouble& Copy ); };
Trouble :: Trouble( int StartValue ) {
Location = new int(StartValue) ; *(test.size) = 20; };
Trouble :: Trouble( const Trouble& Copy ) {
Location = new int( *(Copy.Location) ) ; };
void main() {
Trouble Now;
Trouble ThisIsIt = Now; };
Output
New OK: 10 Kill OK 10
New OK: 10 Kill OK 20
Solution
class OK {
public:
int* size;
OK( int initialSize = 10 );
OK( const OK& Copy );
~OK() {delete size; cout << "Kill OK:" << *size << endl; }; };
// See previous page for OK constructors
class Trouble {
public:
int* Location;
OK test;
Trouble( int StartValue = 5 );
Trouble( const Trouble& Copy ); };
Trouble :: Trouble( int StartValue ) {
Location = new int(StartValue) ; *(test.size) = 20; };
Trouble :: Trouble( const Trouble& Copy ) : test( Copy.test ) {
Location = new int( *(Copy.Location) ) ; };
void main() {
Trouble Now;
Trouble ThisIsIt = Now; };
Output
New OK: 10 Kill OK 20
New Copy OK: 20 Kill OK 20