I am trying to verify that an instance of a class will fit in a queue (defined by a C library), and noticed that sizeof() didn't do what I thought it did.
#include <iostream>
using namespace std;
class A {
int x, y, z;
public:
A() {}
void PrintSize() { cout << sizeof(this) << endl; }
};
class B : public A {
int a, b, c;
public:
B() {}
void PrintSize() { cout << sizeof(this) << endl; }
};
int main() {
A a;
B b;
a.PrintSize(); // is 8
b.PrintSize(); // is 8
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
}
returns:
8
8
12
24
I did not expect the "8" values - why is it different when taken within the class? How can verify that the class that I define fits within a memory space, especially at compile time?
This expression
sizeof(this)
gives the size of the pointer this
. It seems you mean the size of the corresponding class
sizeof( *this )