여기에서 생성자가 호출될 때 볼 수 있습니다. 여기서 생성자는 다양한 유형입니다. 글로벌, 로컬, 정적 로컬, 동적.
전역 객체의 경우 생성자는 기본 함수에 들어가기 전에 호출됩니다.
예시
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
MyClass myObj; //Global object
int main() {
cout << "Inside Main";
} 출력
Calling Constructor Inside Main
객체가 비정적일 때 객체가 생성되는 지점에 도달하면 생성자가 호출됩니다.
예시
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
int main() {
cout << "Inside Main\n";
MyClass myObj; //Local object
cout << "After creating object";
} 출력
Inside Main Calling Constructor After creating object
객체가 로컬 정적일 때 처음에만 해당 생성자가 호출되고 동일한 함수가 다시 사용되더라도 영향을 미치지 않습니다.
예시
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
void func() {
static MyClass myObj; //Local static object
}
int main() {
cout << "Inside Main\n";
func();
cout << "After creating object\n";
func();
cout << "After second time";
} 출력
Inside Main Calling Constructor After creating object After second time
마지막으로 동적 객체의 경우 new 연산자를 사용하여 객체를 생성할 때 생성자가 호출됩니다.
예시
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
int main() {
cout << "Inside Main\n";
MyClass *ptr;
cout << "Declaring pointer\n";
ptr = new MyClass;
cout << "After creating dynamic object";
} 출력
Inside Main Declaring pointer Calling Constructor After creating dynamic object