#include<iostream>
#include<conio.h>
usingnamespace std;
class A
{
public:
A()
{
}
};
class B
{
public:
B()
{
}
};
class C
{
public:
int a;
C()
{
}
};
int main()
{
A a1;
cout << sizeof(a1) << endl;
B *b1 = new B();
cout << sizeof(b1) << endl;
C c1;
cout << sizeof(c1) << endl;
getch();
return 0;
}
This code gives us output -
1
4
4
Now how is the memory allocated that in case of Class A it is only 1,
and in Class C it is 4.
And in case of Class B which is declared using new is also 4.
the reason sizeof(b1) is 4 is because b1 is a pointer, pointers are always 4 bytes regardless of what they point to. c1 is bigger in size that a1 because instance of C contain an integer member variable, whereas the A class is empty
Ok well it's platform dependant but if you continue using the same platform pointers will always take up 4 bytes, my point was that the data type pointed to doesn't affect their size
#include <iostream>
struct Foo {
virtualvoid bar() {}
};
int main() {
void (Foo::*fn)() f = &Foo::bar;
std::cout << sizeof( f ) << std::endl;
}
I haven't run this myself, but with gcc I'm betting you get 6.
You need to read up on the standard about pointers. All pointers-to-POD types, yes,
might be the same size. But pointers-to-members, no, not necessarily.