Skip to content

Instantly share code, notes, and snippets.

@uhziel
Created December 18, 2012 15:16
Show Gist options
  • Save uhziel/4328861 to your computer and use it in GitHub Desktop.
Save uhziel/4328861 to your computer and use it in GitHub Desktop.
copy constructor and copy assignment
#include <iostream>
class Foo {
public:
Foo() {
std::cout << "default constructor" << std::endl;
}
Foo(const Foo& rhs) {
std::cout << "copy constructor" << std::endl;
}
Foo& operator=(const Foo& rhs) {
std::cout << "copy assignment" << std::endl;
}
};
int main() {
Foo foo1; // default constructor
Foo foo2(foo1); // copy constructor
Foo foo3 = foo1; // copy constructor
foo3 = foo2; // copy assignment
return 0;
}
#include <iostream>
#include <cassert>
class MyArray {
public:
MyArray() : array(NULL), count(0) {}
MyArray(const MyArray& other) {
int *new_array = new int[other.count];
std::copy(other.array, other.array + other.count, new_array);
array = new_array;
count = other.count;
}
MyArray& operator=(const MyArray& other) {
assert(this != &other);
int *new_array = new int[other.count];
std::copy(other.array, other.array + other.count, new_array);
if (array != NULL) delete [] array;
array = new_array;
count = other.count;
return *this;
}
private:
int *array;
int count;
};
#include <iostream>
class SubFoo {
public:
SubFoo() {
std::cout << "SubFoo default constructor" << std::endl;
}
SubFoo(const SubFoo& rhs) {
std::cout << "SubFoo copy constructor" << std::endl;
}
SubFoo& operator=(const SubFoo& rhs) {
std::cout << "SubFoo copy assignment" << std::endl;
}
};
class Foo {
public:
Foo() {
std::cout << "Foo default constructor" << std::endl;
}
// error
//
// SubFoo default constructor
// Foo copy constructor
// Foo copy assignment
// SubFoo copy assignment
/*
Foo(const Foo& rhs) {
std::cout << "Foo copy constructor" << std::endl;
operator=(rhs);
}
*/
// right
//
// SubFoo copy constructor
// Foo copy constructor
Foo(const Foo& rhs) : subfoo(rhs.subfoo) {
std::cout << "Foo copy constructor" << std::endl;
}
Foo& operator=(const Foo& rhs) {
std::cout << "Foo copy assignment" << std::endl;
subfoo = rhs.subfoo;
}
private:
SubFoo subfoo;
};
int main() {
Foo foo1; // default constructor
Foo foo2(foo1); // copy constructor
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment