Class Memory Allocation Size

Hello Friends,

I have a question for allocation of memory to classes in C++

Pls have a look at the code -


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
#include<conio.h>

using namespace 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.

Pls help me understand this.

Thank You.

DnshPly9
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
@quirkyusername: Pointers are not always 4 bytes.
Hii,

Ok I thought @quirkyusername is right.
But here is contradiction too.

@jsmith can u help me by elaborating how does it work then..???
How is the memory allocated.
anyone...please...

Thanks

DnshPly9
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
Still, why does sizeof(A) give 1?
Because it doesn't contain any member, and the minimum size for a type is 1
http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty
Sigh.

@quirkyusername: Run this:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

struct Foo {
    virtual void 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.


After fixing a compile error:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

struct Foo {
    virtual void bar() {}
};

int main() {
    void (Foo::*fn)() = &Foo::bar;
    std::cout << sizeof( f ) << std::endl;
}


Output is:
8


[EDIT: I'm running 32-bit linux]

[EDIT2: Ok, this time I pasted the fixed code and not the original]
Last edited on
Your code doesn't compile. I change this:
1
2
3
4
5
//void (Foo::*fn)() f = &Foo::bar;
void (Foo::*f)() = &Foo::bar;
//Or
typedef void (Foo::*fn) ();
fn f = &Foo::bar;
Last edited on
Topic archived. No new replies allowed.