why private destructor getting called when obj is created statically
Hi
Why private destructor are getting called when I creates an object of class having private destructor? But not when I creates a normal object.
================================ CASE I ====================================
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
// 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
main finished
Destructor.
| |
================================= CASE II ====================================
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
// myclass.h
#include <iostream>
class MyClass {
public:
void Display();
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 testObj;
std::cout << "main finished!" << std::endl;
return 0;
}
// Error
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
| |
you cannot use a private function/destructor outside of the class. On line 23 you define the object inside [the member function] of the class
Topic archived. No new replies allowed.