(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)
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.
1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With