Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function overloading?

Tags:

c++

embedded

I'll start by saying I understand that that only nonstatic member functions can be virtual, but this is what I want:

  1. A base class defining an interface: so I can use base class pointers to access functions.

  2. For memory management purposes (this is an embedded system with limited ram) I want the overriding functions to be statically allocated. I accept the consequence that with a static function, there will be constraints on how I can manipulate data in the function.

    My current thinking is that I may keep a light overloading function by making it a wrapper for a function that actually is static.

Please forbear telling me I need to re-think my design. This is why I am asking the question. If you'd like to tell me I'm better off using c and using callbacks, please direct me to some reading material to explain the pitfalls of using an object oriented approach. Is there a object oriented pattern of design which meets the requirements I have enumerated?

like image 651
2NinerRomeo Avatar asked Jun 26 '12 21:06

2NinerRomeo


2 Answers

Is there a object oriented pattern of design which meets the requirements I have enumerated?

Yes, plain old virtual functions. Your desire is "the overriding functions to be statically allocated." Virtual functions are statically allocated. That is, the code which implements the functions exists once, and only once, and is fixed at compile/link time. Depending upon your linker command, they are as likely to be stored in flash as any other function.

class I {
  public:
  virtual void doit() = 0;
  virtual void undoit() = 0;
};

class A : public I {
  public:
  virtual void doit () {
    // The code for this function is created statically and stored in the code segment
    std::cout << "hello, ";
  }
  virtual void undoit () {
    // ditto for this one
    std::cout << "HELLO, ";
  }
};

class B : public I {
  public:
  int i;
  virtual void doit() {
    // ditto for this one
    std::cout << "world\n";
  }
  virtual void undoit() {
    // yes, you got it.
    std::cout << "WORLD\n";
  }
};

int main () {
   B b; // So, what is stored inside b?
        // There are sizeof(int) bytes for "i",
        // There are probably sizeof(void*) bytes for the vtable pointer.
        // Note that the vtable pointer doesn't change size, regardless of how
        // many virtual methods there are.
        // sizeof(b) is probably 8 bytes or so.
}
like image 88
Robᵩ Avatar answered Sep 22 '22 15:09

Robᵩ


For memory management purposes (this is an embedded system with limited ram) I want the overriding functions to be statically allocated.

All functions in C++ are always statically allocated. The only exception is if you manually download and utilize a JIT.

like image 29
Puppy Avatar answered Sep 20 '22 15:09

Puppy