vendredi 11 mai 2018

sizeof(*this) and decltype(*this) in derived classes

Suppose there are classes:

struct A {
  int a;

  virtual size_t GetMemoryUsage() const {
    return sizeof(*this);
  }
}

struct B : public A {
  int b;
}

And there may be deeper inheritance.

What I want is to have a method which will return the number of bytes an object occupies in memory, GetMemoryUsage() in this case. Usually it can be achieved by using sizeof(*this). The problem is (at least AFAIU) that I have to override the method in each derived class and actually copy-paste its body. I don't like duplicated code :)

Am I correct? How can I make sizeof(*this) and decltype(*this) return what I want in subclasses, by calling them only from base class's methods? Is there a more elegant solution?

Aucun commentaire:

Enregistrer un commentaire