Search code examples
c++c++11c++14sizesizeof

Object size of base class while referring to derived class


#include<bits/stdc++.h>

using namespace std;

class abc {
  public:
    int a = 45;
  void sum() {
    int s = 55;
    cout << s + a << endl;
  }
};
class xyz: public abc {
  public: int b = 45;
  int c = 54;
  int d = 96;
  int x = 8;
  void show() {
    cout << "xyz class" << endl;
  }
};
int main() {
  abc * ob;
  xyz d;
  ob = & d;
  cout << sizeof( * ob) << endl;
}

Why does sizeof function return 4 in this case? From where I stand, the pointer ob is pointing to an already created object d of derived class xyz whose size is 20. So sizeof(*ob) should also return this value: 20.


Solution

  • The sizeof operator deals with static types, not dynamic ones. *ob is of static type abc, so that's the size it returns.

    Note that sizeof is performed at compile time, and there is no way that the compiler could figure out the dynamic type of an instance that is part of an inheritance hierarchy. In your snippet, it looks like this kind of lookup could be easily performed, but imagine

    abc *ob;
    
    sizeof(*ob);
    

    anywhere in some other translation unit, where xyz is not even known.