-
Notifications
You must be signed in to change notification settings - Fork 0
/
eg_CopyConstructor.cpp
83 lines (68 loc) · 1.67 KB
/
eg_CopyConstructor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <iostream>
#include <string>
using namespace std;
const string unk = "unknown";
const string clone_prefix = "clone-";
class Animal
{
string _type = "";
string _name = "";
string _sound = "";
public:
Animal(); // default constructor
Animal(const string& type, const string& name, const string& sound); // constructor with 3 arguments
Animal(const Animal&); // copy constructor
Animal& operator = (const Animal&); // copy operator
~Animal(); // default destructor
void print() const;
};
Animal::Animal() : _type(unk), _name(unk), _sound(unk)
{
puts("default constructor");
}
Animal::Animal(const string& type, const string& name, const string& sound) : _type(type), _name(name), _sound(sound)
{
puts("constructor with arguments");
}
Animal::Animal(const Animal& rhs)
{
puts("copy constructor");
this->_type = rhs._type;
this->_name = clone_prefix + rhs._name;
this->_sound = rhs._sound;
}
Animal::~Animal()
{
cout << "destructor: "<< this->_name << " the " << this->_type << endl;
}
Animal& Animal::operator = (const Animal& rhs)
{
puts("copy operator");
if(this != &rhs)
{
this->_type = rhs._type;
this->_name = clone_prefix + rhs._name;
this->_sound = rhs._sound;
}
else
{
puts("same object copy is prohibited");
}
return *this;
}
void Animal::print() const
{
cout << this->_name << " the " << this->_type << " says " << this->_sound << endl;
}
int main()
{
Animal a;
a.print();
const Animal b("cat","fluffy","meow");
b.print();
a = b;
a.print();
const Animal d = a;
d.print();
return 0;
}