Re: private constructor and new operator overloading.
On May 11, 11:27 am, siddhu <siddharth....@gmail.com> wrote:
Dear Experts,
I want to make a class whose objects can be created only on heap.
I used the following approach.
class ss
{
ss(){}
public:
void* operator new(size_t sz)
{
cout<<"in new"<<endl;
return new char[sz];
}
void operator delete(void* m)
{
free(m);
}
};
int main()
{
ss* s = new ss;
return 0;
}
But when I do
ss* s = new ss;
compiler complains that constructor ss::ss() is private.
As operator new function is member of class so compiler should not
complain because operator new function can call the default
constructor even if it is private.
I am surprised and confused.
Suggestions would be of great help.
Regards,
Siddharth
These dynamic containers also store their elements on the heap.
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <list>
class A { };
int main()
{
std::vector< int > vn(100, 0); // 100 integers initialized to 0
std::deque< std::string > ds(10, "default string"); // 10 strings
std::list< A > la(20);
}