OOP C8 Copy constructor

Copying is to create a new object from an existing one. It is imlplemented by the copy constructor.

1
2
3
4
5
6
7
8
void func(Currency p) { 
cout << "X = " << p.dollars();
}
...
Currency bucks(100, 0);
func(bucks); // bucks is copied into p
Currency a(bucks); //copy constructor called
Currency a = bucks; //also copy constructor called
C++

The copy constructor

1
T::T(const T&);
C++
  • Call-by-reference is used for the explicit argument
  • C++ builds a copy ctor for you if you don’t provide one!
    • The copy ctor by C++ copies each member variable.
    • It is Good for numbers, objects, arrays since it copies each pointer
    • Data may become shared!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cstring> // #include <string.h>
using namespace std;
Person::Person( const char *s ) {
name = new char[::strlen(s) + 1];
::strcpy(name, s);
}
Person::~Person() {
delete [] name;
}
// array delete
Person::Person( const Person& w ) {
name = new char[::strlen(w.name) + 1];
::strcpy(name, w.name);
}
C++

About strcpy:

1
char *strcpy (char *dest, const char *src);
C++

strcpy copies src to dest stopping after the terminating null-character is copied.

  • src should be null-terminated!
  • dest should have enough memory space allocated to contain src string.
  • Return Value: returns dest

copy ctors calling

  • call functions by value:
1
2
3
void roster( Person ); // declare function 
Person child( "Ruby" ); // create object
roster( child ); // call function
C++
  • initialization:
1
2
3
4
5
//normal initialization
Person baby_a("Fred");
// these use the copy ctor
Person baby_b = baby_a;
Person baby_c( baby_a );
C++
  • function return:

    1
    2
    3
    4
    5
    6
    7
    Person captain() { 
    Person player("George");
    return player;
    }
    ...
    Person who("");
    ...
    C++

Avoid copy ctor?

  • Compilers can “optimize out” copies when safe!
1
2
3
4
5
6
7
8
Person copy_func( char *who ) { 
Person local( who );
local.print();
return local; // copy ctor called!
}
Person nocopy_func( char *who ) {
return Person( who );
} // no copy needed!
C++

How to write copy ctor?


OOP C8 Copy constructor
http://example.com/2023/05/16/OOP-8/
Author
Tekhne Chen
Posted on
May 16, 2023
Licensed under