[객체지향프로그래밍(2)] 소멸자(Destructor)
by 브이담곰🌜 요즘 1주일 반동안 질의응답하느라 수업진도를 나가지 않았다. 내 입장에서는 복습할 시간이 늘어나니까, 좋긴한데 한편으로는 새로운게 배우고 싶긴하당..ㅎㅎ
📌 Destructor
- called automatically at the end of the object's life in charge of releasing this memory.
- no arguments and returns nothing, not even void.
- uses the class name as its own name, but preceded with a tilde sign (~):
// destructors
#include <iostream>
#include <string>
using namespace std;
class Example4 {
string* ptr;
public:
// constructors:
Example4() : ptr(new string) {}
Example4 (const string& str) : ptr(new string(str)) {}
// destructor:
~Example4 () {delete ptr;}
// access content:
const string& content() const {return *ptr;}
};
int main () {
Example4 foo;
Example4 bar ("Example");
cout << "bar's content: " << bar.content() << '\n';
return 0;
}
✔ If prgrammers call the destructor before the program ended. That way means just calling function of the name ~desctroctor();.
It's not mean the objects' delete, after calling the objects' destructor forcely while the project running. Real destrocter is called at the end of the project.
🙋♀️ Case of calling destructor by forced.
class Sample()
{
private:
int a;
public:
~Sample();
Sample(int _a);
};
Sample::Sample(int _a) : a(_a)
{
cout<<"create : " << _a << endl;
}
Sample::~Sample
{
cout<<"delete : " << _a << endl;
}
int main()
{
Sample sample_1(1);
Sample sample_2(2);
sample_1.~Sample(); //just call ~sample as function. not destructor type.
cout<<"--------program finish----------"<<endl;
return 0;
}
//now real destroctors are called.
'programming > C++' 카테고리의 다른 글
[객체지향프로그래밍(2)]Finals Test Report : HelicopterGame만들기. (0) | 2021.12.18 |
---|---|
[객체지향프로그래밍(2)]Finals Test Report : Map Editor만들기. (0) | 2021.12.09 |
[객체지향프로그래밍(2)] Midterm Test Report #2번 풀이 (0) | 2021.11.06 |
[객체지향프로그래밍(2)] Midterm Test Report #1번 풀이 (0) | 2021.11.05 |
[객체지향프로그래밍(2)] rand()와 srand()의 차이 (0) | 2021.09.14 |
블로그의 정보
농담곰담곰이의곰담농
브이담곰