Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof *this object

Tags:

c++

Code:

#include <cstdio>

class myc {
    int dummy;
public:
    int si(){return sizeof(*this);}
};

class d_myc : public myc {
    int d_dummy;
};

int main() {
    myc a;
    d_myc b;
    printf("%d %d\n%d %d", a.si(), b.si(), sizeof(a), sizeof(b));
    return 0;
}

output :

4 4
4 8

I expected :

4 8
4 8

Why were my expectations wrong?

like image 293
all Avatar asked Aug 12 '11 00:08

all


2 Answers

This is resolved at compile time:

class myc {
    int dummy;
public:
    int si(){return sizeof(*this);}
};

i.e. *this is always myc and will never be d_myc. To get what you want you will have to override the function in d_myc to do the same in the derived as the base. This is because sizeof(d_myc) includes the base class too.

like image 139
fwg Avatar answered Nov 12 '22 14:11

fwg


sizeof is resolved at compile-time, not run-time. So sizeof(*this) is equivalent to sizeof(myc).

like image 23
Oliver Charlesworth Avatar answered Nov 12 '22 16:11

Oliver Charlesworth