I'm very new in C++ and was confused by the following example:
#include <iostream>
#include <cstddef>
#include <cstdlib>
class Test{
public:
enum test_type{ test1 = 0, test2, test3};
void *operator new(size_t sz, test_type t){
return malloc(sz);
}
};
class SomeClass: public Test{
public:
SomeClass(int a): a(a){}
int a;
};
int main(int argc, char ** argv){
SomeClass *sc = new(Test::test1) SomeClass(10);
std::cout << sc->a << std::endl;
}
I read name lookup rules in the cpp-reference page, but did not find any explanation about why the operator new defined in the base class was found and used for derived class (which can potentially contain an additional member).
Is it a common way to declare operator new
in a base class and then use it to allocate memory for derived classes (the idea was taken from some open-source project written in C++)?