728x90
반응형
#include <iostream>
using namespace std;
class Simple
{
private:
int num1;
int num2;
public:
Simple(int n1, int n2) : num1(n1), num2(n2)
{
// empty
}
// Copy Constructor
// "If undefined Copy constructor, auto insert default COPY CONSTRUCTOR"
// Parameter of copy constructor MUST BE REFERENCE.
// Keyword: explicit (for clarity of code)
// If doesn't want call default copy constructor, should to use this Keyword.
explicit Simple(const Simple& copy) : num1(copy.num1), num2(copy.num2)
{
cout << "Called SoSimple(SoSimple& copy)" << endl;
}
void ShowInfo() const
{
cout << "num1: " << num1 << endl;
cout << "num2: " << num2 << endl;
cout << "Addr: " << this << endl;
}
};
int main(void)
{
Simple a(1, 2);
Simple b(a);
// Generate Object type of 'Simple'
// Object name is 'b'
// Object generation is completed through
// a call from a constructor who can receive sim1 as a argument.
// Different Addreess each(Shallow Copy)
// Equal Member variable value each
a.ShowInfo(); // 2A342FFBF8
b.ShowInfo(); // 2A342FFC18
return 0;
}
/*
The default constructor copies members to members.
This is called shallow copy.
This is a problem if the member variable refers to the memory space of the heap.
*/
728x90
반응형
'Language > C & C++' 카테고리의 다른 글
Function practice (0) | 2022.10.19 |
---|---|
[Instant]Homework (0) | 2022.10.18 |
[C++] this pointer (0) | 2022.10.17 |
[C++] Object Array (0) | 2022.10.17 |
[C++] Constructor & Destructor (0) | 2022.10.17 |