
생성자(constructor)와 소멸자 (destructor)라는 멤버함수는 사용자가 꼭 정의하지 않아도 되는 함수이다. 그렇다고 해서 존재하지 않는 것은 아니며 시스템 내부에서 언제나 객체의 생성과 소멸을 담당한다.
<생성자(constructor)>
생성자는 사용자가 특별히 지정하지 않아도 자동으로 호출되지만 멤버에 대한 초기화 자료를 지정하지 않으면 객체 멤버변수들은 쓰레기(garbage) 값을 갖는다. 즉, 생성자는 주로 멤버변수의 초기화를 한다.
<특징>
1. 생성자의 이름은 클래스명과 같다.
2. 클래스의 객체가 생성될 때마다 자동으로 호출된다.
3. 보통 객체가 메모리에 할당될 때 멤버변수의 초기화를 담당한다.
4. 리턴형을 쓰지 않는다.
5. 생성자가 반드시 있어야 하는 것은 아니지만 메모리를 초기화 한다는 의미에서 있는 것이 좋다.
<초기화>
변수의 초기화
int num=5; char ch='A'; double avg=0.0; int *pnum=# char *name="Han";배열의 초기화
int sd[3]={1,2,3}; char name[4]={'H','a','n','\0'};구조체 변수(객체)의 초기화
struct SCORE{ char name[15]; int kor; }; struct SCORE h={"하니",90};
<멤버 변수 초기화>
#include <iostream> using std::cout; class Dog { private: int age=1; public: int getAge(); void setAge(int a); }; int Dog::getAge(){ return age; } void Dog::setAge(int a){ age = a; } int main(){ Dog happy,coco; cout << happy.getAge()<<coco.getAge(); return 0; }
<private멤버변수를 특정 값으로 초기화하는 생성자>
#include <iostream> using std::cout; class Dog{ private: int age; public: Dog(){age=1;} <생성자 정의, Dog():age(1){ }, Dog():age{1}{ }> int getAge(){return age;} void setAge(int a){age=a;} }; int main() { Dog happy; <happy객체가 생성되는 순간 생성자가 자동 호출됨> cout<<happy.getAge(); return 0; }#include <iostream> using std::cout; class Dog{ private: int age; public: Dog(); // 생성자 선언 int getAge(); void setAge(int a); }; Dog::Dog() <생성자 정의, 리턴형을 쓰면 안됨> { age=1; <private멤버변수 Age를 초기화> } int Dog::getAge() { return age; } void Dog::setAge(int a) { age=a; } int main() { Dog happy; <happy객체가 생성되는 순간 생성자가 자동 호출됨> cout<<happy.getAge(); return 0; }
<C++에서 변수를 초기화 하는 방법>
#include <iostream> int main() { int x=1; <copy initialization,비추> int y(2); <direct initialization> int z{3}; <Uniform initialization, C++11> int z1{}; <Uniform initialization, 자동으로 0,C++11> std::cout << x << y << z << z1; }
<생성자의 매개변수로 멤버변수 초기화>
#include <iostream> using std::cout; class Dog { private: int age; public: Dog(int a) { age = a; } int getAge() { return age; } void setAge(int a) { age = a; } }; int main() { Dog coco(4); <4는 생성자로 넘어감> Dog coco1{ 3 }; <Uniform initialization> Dog coco2 = Dog(2); <비추> Dog coco3 = 1; <비추> cout << coco.getAge() << coco1.getAge() << coco2.getAge() << coco3.getAge(); return 0; }#include <iostream> using std::cout; class Dog { private: int age; public: Dog(int a) :age(a) {} //initializer list // Dog(int a):age{a}{} int getAge() { return age; } void setAge(int a) { age = a; } }; int main() { Dog coco(4); <4는 생성자로 넘어감> Dog coco1{ 3 }; <Uniform initialization> Dog coco2 = Dog(2); <비추> Dog coco3 = 1; <비추> cout << coco.getAge() << coco1.getAge() << coco2.getAge() << coco3.getAge(); return 0; }
<소멸자(destructor)>
클래스의 객체가 소멸될 때 자동으로 호출된다 소멸자의 이름은 클래스명과 같고, 앞에 ~(tilde)를 붙인다. 리턴형과 매개변수가 없다. 객체가 소멸될 때 자동으로 호출되므로 객체가 소멸될 때 하고 싶은 코드를 작성한다. 소멸자는 사용한 메모리 공간이 더 이상 불필요하게 될 때 해당 메모리를 시스템이나 다른 객체에 반납하는 용도로 많이 사용하는 함수이다.
<객체가 소멸되면서 "소멸"이라고 출력되는 소멸자>
#include <iostream> using std::cout; class Dog { private: int age; public: Dog(int a) { age = a; cout << "멍\n"; } ~Dog() { cout << "소멸\n"; } <소멸자 정의> int getAge(); void setAge(int a); }; int Dog::getAge() { return age; } void Dog::setAge(int a) { age = a; } int main() { Dog happy(5); cout << "main함수 시작\n"; cout << happy.getAge(); cout << "\nmain함수 끝\n"; return 0; }