C++/class
[C++] 상속과 생성자/소멸자
year.number
2022. 7. 8. 09:02
생성자는 객체가 생성될 때 자동으로 호출된다.
자식 클래스의 객체가 생성될 때, 부모 클래스의 생성자도 호출될까?
자식 클래스 생성자보다 부모 클래스의 생성자가 먼저 묵시적으로 호출된다. 단, 소멸자의 경우에는 역순으로 호출된다.
부모 클래스의 생성자를 호출하는 방법
Rectangle(int x = 0, int y = 0, int w = 0, int h = 0) : Shape(x, y){
width = w;
height = h;
}
#include <iostream>
#include <string>
using namespace std;
class Shape{
public:
int x; int y;
Shape(){
x = 0; y = 0;
cout << "Shape 생성자()" << endl;
}
Shape(int x, int y){
this->x = x; this->y = y;
cout << "Shape 생성자(x, y)" << endl;
}
~Shape(){
cout << "Shape 소멸자()" << endl;
}
};
class Rectangle : public Shape{
public:
int width; int height;
Rectangle(){
width = 0; height = 0;
cout << "Rectangle 생성자()" << endl;
}
Rectangle(int x, int y, int width, int height) : Shape(x, y){
this->width = width;
this->height = height;
cout << "Rectangle 생성자(x, y, w, h)" << endl;
}
~Rectangle(){
cout << "Rectangle 소멸자()" << endl;
}
};
int main(){
Rectangle rr(0,0,10,10);
return 0;
}
출력 결과