0

Is it possible to create an instance of a class on a heap without calling default constructor and with a valid vtable for inheritance? Let me demonstrate what I will like to do:

class A
{
  protected: virtual void _fake_static_method()
  {

  }
};

class B1 : public A
{
  protected: virtual void _fake_static_method()
  {
    std::cout << "Hello";
  }

  public: static void run_fake_static_method()
  {
    B1* dummy = static_cast<B1*>(::operator new(sizeof(B1)));
    dummy->_fake_static_method();
    free(dummy);
  }
}

class B2 : public A
{
  public: static void run_fake_static_method()
  {
    B2* dummy = static_cast<B2*>(::operator new(sizeof(B2)));
    dummy->_fake_static_method();
    free(dummy);
  }
}

Here I want to call a static method from example B1::run_fake_static_method(). In that method I want to run a member method, but I don't want to call the default constructor. I need such an implementation to remove the virtual method without a compiling error among other errors. Like a "virtual static method" I hope you understand what I want to do.

Is there a special trick that I can get this to work? :)

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Alexander
  • 471
  • 4
  • 18
  • 5
    Yes. Call a different constructor. – juanchopanza Jul 09 '14 at 18:28
  • `#define virtual static` - technically UB though. – Flexo Jul 09 '14 at 18:31
  • 2
    You can't mix `operator new` and `free` like that. And can you explain what exactly do you mean with "remove the virtual method without error"? – jrok Jul 09 '14 at 18:34
  • Obvious undefined behavior is obvious. – T.C. Jul 09 '14 at 18:41
  • 4
    ...X vs Y problem anyone? (To clarify, what you are doing may be possible, but what are you trying to do with it? There is probably a better pattern out there that will do what you want without being broken as hell) – IdeaHat Jul 09 '14 at 18:42
  • 1
    In order to call a non-static member function you must have an object. To have an object you must call a constructor. Not necessarily the default one, any constructor will do, but you must call one. – n. m. could be an AI Jul 09 '14 at 19:07
  • To add to what @n.m. said, calling any non-static member on an object that hasn't been constructed would be undefined behavior. Undefined behavior can make your life hell in mysterious ways - don't go there. – Mark Ransom Jul 09 '14 at 19:57

0 Answers0