struct Base {
uint8_t a{};
uint8_t b{};
size_t size() { return sizeof(*this); }
};
struct Derived: public Base{
uint8_t c{};
};
int main() {
Base* b = new Base();
Derived* d = new Derived();
std::cout << b->size() << "n"; // prints 2 // correct
std::cout << d->size() << "n"; // prints 2 // incorrect, should be 3
}
I stumbled upon this interesting problem. I know it is incorrect because I am not using virtual function here. But if I use virtual, the size also includes the size of vtable.
If I use virtual size_t size() { return sizeof(*this); }
, the output of both the print statements is 16.
How can I write a function in base class which will give me the total size of only member variables?
Not sure if there is a way to do that