String str1('A', 3); // 일반 생성자 호출 1
String str2 = str1; // 복사 생성자 호출 2
혹은
String str2(str1); // 복사 생성자 호출
❗ 1. 대입 연산자인 operator=() 멤버함수는 이미 생성된 객체에서만 호출되는 반면에 복사 생성자는 새로운 객체를 만들 때 호출된다. 따라서 operator=() 멤버함수는 원래 할당했던 메모리를 해제하고 새로 할당을 해야하지만, 복사 생성자는 객체가 처음 생성되는 시점이기 때문에 그럴 필요가 없다.
대입 연산자인 operator=() 멤버함수는 자기 자신의 객체를 대입하였는지 검사해야하지만, 복사 생성자는 자기 자신의 초기화가 불가능하기 때문에 그럴 필요가 없다.
대입 연산자인 operator=() 멤버함수는 다중 대입문을 지원해야하므로 *this를 반환해야 하지만, 복사 생성자는 생성자이기 때문에 반환값을 가질 수 없다.
#include<iostream>
using namespace std;
class Employee
{
public:
Employee();
Employee(const char* pName, const char* pAddr);
~Employee();
void DisplayEmployee();
private:
char* strName;
char* strAddr;
};
Employee::Employee()
{
strName = NULL;
strAddr = NULL;
}
Employee::Employee(const char* pName, const char* pAddr)
{
strName = new char[strlen(pName) + 1]; // strlen : 문자열 길이 리턴해주는 함수
strAddr = new char[strlen(pAddr) + 1]; // \n값까지 포함해야해서 + 1
strcpy_s(strName, strlen(pName) + 1, pName);
strcpy_s(strAddr, strlen(pAddr) + 1, pAddr);
}
Employee::~Employee()
{
delete strName;
delete strAddr;
}
void Employee::DisplayEmployee()
{
cout << "이름 : " << strName << endl;
cout << "주소 : " << strAddr << endl;
}
void main()
{
Employee emp("kim", "seoul");
emp.DisplayEmployee();
}
class 자식 클래스명 : 접근 지정자 부모 클래스명
{
public:
반환형 함수명(매개변수);
private:
데이터형 변수명;
}
class Regular : Employee
{
public:
Regular();
Regular(char* pName, char* pAddr, double dSalary);
~Regular();
double payCheck() const;
private:
double salary;
}
Regular 클래스는 Employee 클래스의 이름, 주소에 대한 멤버 변수들을 상속받았다.
Regular 클래스는 급여액 관련 멤버 변수 salary와 멤버함수 PayCheck() 함수만 별도 선언하였다.
이러한 부모 클래스와 자식 클래스 간의 관계를 '상속성'이라고 한다.