In the code below, I am not getting the
- use/reasons/benefits of making MyClass::~MyClass() destructor private?
- Since the destructor is private, so how the destructor are getting called at the end.
// myclass.h #include <iostream> class MyClass { public: static MyClass& GetInstance(); void Display(); private: MyClass(); virtual ~MyClass(); };
MyClass::MyClass() {
std::cout << "Constructor " << std::endl;
}
MyClass::~MyClass() {
std::cout << "Destructor" << std::endl;
}
MyClass& MyClass::GetInstance() {
static MyClass _instance;
return _instance;
}
void MyClass::Display() {
std::cout << "Hello" << std::endl;
}
// main.cpp
#include "myclass.h"
#include <iostream>
int main() {
MyClass::GetInstance().Display(); //case1
std::cout << "main finished!" << std::endl;
return 0;
}
//Output
Constructor
Hello
Destructor
// Edit
if I make the Contructor of my class public and remove the GetInstance() function.
> MyClass obj;
> obj.Display();
Then the following error pops up
1>e:\programs\cpp_test\src\main.cpp(38): error C2248: 'MyClass::MyClass' : cannot access private member declared in class 'MyClass'
1> e:\programs\cpp_test\static_single_test.h(11) : see declaration of 'MyClass::MyClass'
1> e:\programs\cpp_test\static_single_test.h(6) : see declaration of 'MyClass'
1>e:\programs\cpp_test\src\main.cpp(38): error C2248: 'MyClass::~MyClass' : cannot access private member declared in class 'MyClass'
1> e:\programs\cpp_test\static_single_test.h(12) : see declaration of 'MyClass::~MyClass
'
Question: How making how static case is being handled by c++? Is is not overriding the private behaviour?