Using virtual keyword spends too much RAM

Today I noticed that I suddenly spent about 38 bytes to nowhere. I was examining changes in the code.

Finally I realized that this significant change was made by adding virtual to a function. I started experimenting with virtual adding it in different places. Sometimes it takes 8 bytes, sometimes, just 2.

For my upset, I can’t predict how much RAM I will spend next time. Anybody knows how it works?

You need to research C++ vtable.

TheMemberFormerlyKnownAsAWOL:
You need to research C++ vtable.

I did. And I don’t understand why another virtual allocates 38 bytes. I have not event extended this class yet. So as to me, it was supposed to allocate about 4 bytes only. However, I can see that this amount if different for different situations. That’s what I’m asking about.

This is just one example of the many reason why C++ is generally avoided (in favor of C) in small embedded systems. Vtables, RTTI, exception frames, etc. all have overhead. Using any C++ features beyond what C already offers should be a deliberate decision with a full understanding of the implications.

I know all these warnings.
I am trying to be careful with C++ features and always think whether it is worthy to do some C++ stuff.

Nonetheless the question still exists ;-).

zhekaus:
Nonetheless the question still exists ;-).

I think it might help if you could show a small example where the 'virtual' keyword takes an additional 38 bytes of RAM.

C++ compilers are usually expected to optimize primarily for speed, not space. The compiler won't have been rewritten specially for an 8-bit microcontroller, just the code-generator support added. On typical computer hardware 38 bytes is down in the noise, on an 8-bit microcontroller its significant.

MarkT:
C++ compilers are usually expected to optimize primarily for speed, not space. The compiler won’t have been rewritten specially for an 8-bit microcontroller, just the code-generator support added. On typical computer hardware 38 bytes is down in the noise, on an 8-bit microcontroller its significant.

You can specify how the compiler optimize your code (or not at all) via specific flags.
I believe for the avr, the flags are set to optimize for space at the most aggressive level instead of for speed.

Another disadvantage of using virtual functions is that they are always linked in even if not used.
There used to be a way to set things up in the code and use some special compiler options to avoid this but it was taken way in newer versions of gcc.

This is very different from “normal” functions which you can tell the compiler and linker to remove from the final linked image if not used.

Virtual functions can be convenient from a development & maintenance perspective but they carry a cost in terms of additional overhead in image size and call overhead.

— bill