When I try compiling the following:
#include <iostream>
class Test
{
public:
void* operator new (size_t num);
void operator delete (void* test);
~Test();
private:
Test();
};
Test::Test()
{
std::cout << "Constructing Test" << std::endl;
}
Test::~Test()
{
std::cout << "Destroying Test" << std::endl;
}
void* Test::operator new (size_t num)
{
::new Test;
}
void Test::operator delete(void* test)
{
::delete(static_cast<Test*>(test));
}
int main()
{
Test* test = new Test;
delete test;
}
I get :
$ g++ -o test test.cpp
test.cpp: In function ‘int main()’:
test.cpp:14: error: ‘Test::Test()’ is private
test.cpp:36: error: within this context
If the new is a member function, why can it not call the private constructor?
Edit:
My idea is to create a class that can only be instantiated on the heap using totally standard syntax. I was hoping since new is a data member, it could call the private constructor but since new is not used for stack objects, you would not be allowed to create the object on the stack.
I think you have a misunderstanding on what the
operator newdoes. It does not create objects, but rather allocates memory for the object. The compiler will call the constructor right after calling your operator new.The main usage of the operator new is having a memory allocator different to the default allocator for the system (usually malloc), and it is meant to return an uninitialized region of memory on which the compiler will call the constructor. But the constructor is called after the memory is allocated in the scope where the new call was written (main in this case).
After acceptance note
The complete solution to the unformulated question: how do I force users of my class to instantiate in the heap? is to make the constructors private and offer a factory function, as shown in some other answers (as the one by villintehaspam) point out.