반응형
디폴트 복사 생성자란, 말 그대로 따로 지정해주지 않아도 기본으로 생성되는 생성자를 말한다.
#include <iostream>
#include<cstring>
using namespace std;
class People {
int age;
char* name;
public:
People(int age, const char* name) {
this->age = age;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
/*People(People& pl):age(pl.age) { //이 함수가 없으면 디폴트 복사 생성자가 자동으로 생성이 된다.
this->name = new char[strlen(pl.name) + 1];
strcpy(this->name,pl.name);
}*/
~People() {
delete []name;
cout << "Called Destructor" << endl;
}
void Show() {
cout << "\nname :" << name;
cout << "\nage :" << age<<endl;
}
};
int main(void)
{
People pl(23, "minsu");
People me(pl);
pl.Show();
me.Show();
}
디폴트 복사 생성자는 얕은 복사(shallow copy)이다.
그리고 주석처리한 함수는 깊은 복사를 하기 위해 명시적으로 생성자를 만들어 준 것이다.
이는 깊은 복사(deep copy)이다.
얕은 복사와 깊은 복사에 차이점은 나중에 자세히 설명하겠다.
이 둘은 큰 차이가 있다는 것만 알아 두면 좋을것 같다.
반응형
'c++' 카테고리의 다른 글
값에 의한 호출 call by value (0) | 2021.08.26 |
---|---|
매개변수의 디폴트 값 (Default Value) (0) | 2021.08.26 |
[c++] 문자열 동적 할당하여 저장하기 (0) | 2021.02.09 |
[c++] 상속자(Constructor)와 멤버 이니셜라이저(Member Initalizer) (0) | 2021.02.09 |
[c++] 정보 은닉 (Information Hiding) (0) | 2021.02.09 |