반응형
DynamicParents.h
#pragma once #includeDynamicParents.cpp#include #include class DynamicParents { protected: char* s; public: virtual void printString(); public: DynamicParents(const char* p); virtual ~DynamicParents(); }; class DynamicParents_noVirtual { protected: char* s; public: virtual void printString(); public: DynamicParents_noVirtual(const char* p); ~DynamicParents_noVirtual(); };
#include "DynamicParents.h" void DynamicParents::printString() { std::cout << s << std::endl; } DynamicParents::DynamicParents(const char* p) { std::cout << " Parents 생성자" << std::endl; s = new char[strlen(p) + 1]; strcpy_s(s, strlen(p) + 1, p); } DynamicParents::~DynamicParents() { std::cout << " Parents 소멸자" << std::endl; delete[] s; } void DynamicParents_noVirtual::printString() { std::cout << " " << s << std::endl; } DynamicParents_noVirtual::DynamicParents_noVirtual(const char* p) { std::cout << " Parents 생성자" << std::endl; s = new char[strlen(p) + 1]; strcpy_s(s, strlen(p) + 1, p); } DynamicParents_noVirtual::~DynamicParents_noVirtual() { std::cout << " Parents 소멸자" << std::endl; delete[] s; }DynamicChild.h
#pragma once #include "DynamicParents.h" class DynamicChild : public DynamicParents { private: char* tag; public: void printString(); public: DynamicChild(const char* t, const char* p); virtual ~DynamicChild(); }; class DynamicChild_noVirtual : public DynamicParents_noVirtual { private: char* tag; public: void printString(); public: DynamicChild_noVirtual(const char* t, const char* p); virtual ~DynamicChild_noVirtual(); };DynamicChild.cpp
#pragma once #include "DynamicChild.h" void DynamicChild::printString() { std::cout << " " << tag << s << tag << std::endl; } DynamicChild::DynamicChild(const char* t, const char* p) : DynamicParents(p) { std::cout << " child 생성자" << std::endl; tag = new char[strlen(t) + 1]; strcpy_s(tag,strlen(t)+1,t); } DynamicChild::~DynamicChild() { std::cout << " child 소멸자" << std::endl; delete[] tag; } void DynamicChild_noVirtual::printString() { std::cout << " " << tag << s << tag << std::endl; } DynamicChild_noVirtual::DynamicChild_noVirtual(const char* t, const char* p) : DynamicParents_noVirtual(p) { std::cout << " child 생성자" << std::endl; tag = new char[strlen(t) + 1]; strcpy_s(tag, strlen(t) + 1, t); } DynamicChild_noVirtual::~DynamicChild_noVirtual() { std::cout << " child 소멸자" << std::endl; delete[] tag; }main.cpp
#include "DynamicChild.h" int main() { { std::cout << "가상 소멸자가 없으면" << std::endl; DynamicParents_noVirtual* x = new DynamicChild_noVirtual("--", "메모리 누수 있음"); x->printString(); delete x; std::cout << "자식 소멸자가 호출되지 않음" << std::endl; } std::cout << std::endl; { std::cout << "가상 소멸자가 있으면" << std::endl; DynamicParents* o = new DynamicChild("--", "메모리 누수 없음"); o->printString(); delete o; std::cout << "부모 생성자, 자식 생성자, 자식 소멸자, 부모 소멸자 다 호출 됨" << std::endl; } }
반응형