Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent inheriting operator new and delete

(I did scan, but couldn't find anything similiar, if dupe please close).

Is there a way to prevent these two operators from being inherited? For example:

struct foo{
  static void* operator new(std::size_t) { 
    // special
  }
  static void operator delete(void* p, std::size_t) { 
    // special
  }
};    

struct bar : public foo {
};

Now bar will inherit the two operators - in this trivial case, not such a big deal, problem arises if there are data members in foo and bar (and worse in my case, as allocation for foo needs to be done differently to bar!) Now the way to avoid this is that in bar, I would implement the operators too. However if there are lots of derived types, the likelyhood of forgetting to override somewhere is quite possible. So question is, is there a way to prevent these operators from being inherited?

NOTE: c++03 (and willing to accept some compiler specific solution if it's specific to gcc)

like image 615
Nim Avatar asked Aug 25 '11 10:08

Nim


People also ask

Why overload new and delete operators?

Why to overload new and delete? 1. The overloaded new operator function can accept arguments; therefore, a class can have multiple overloaded new operator functions. This gives the programmer more flexibility in customizing memory allocation for objects.

Can I create new operators using operator overloading?

1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed.

Are overloaded operators inherited?

All overloaded operators except assignment (operator=) are inherited by derived classes. The first argument for member-function overloaded operators is always of the class type of the object for which the operator is invoked (the class in which the operator is declared, or a class derived from that class).

Can operator be inherited in C++?

In C++, like other functions, assignment operator function is inherited in derived class. For example, in the following program, base class assignment operator function can be accessed using the derived class object.


1 Answers

You could define an intermediate foo which calls global new/delete again and derive from that.

class foo_without_new : public foo
{
protected: 
 foo_without_new(){} // only derived types should be able to construct foo_without_new!
public:    
 void *operator new(size_t sz) 
 { 
     return ::operator new(sz);
 }
 void operator delete(void*p) 
 { 
     return ::operator delete(p);
 }
}; 

class Bar : public FooWithoutNew
{
};

There is some more work involved if you have to forward constructors of course.

like image 68
Nordic Mainframe Avatar answered Oct 09 '22 19:10

Nordic Mainframe