sizeof and a class with virtual members

C

Chameleon

The code is:
-----------------------------------------------
#include <cstdio>

#define S(X) printf(#X ": %d\n", sizeof(X));

class Seekable
{
public:
virtual void seek(int to, char from);
virtual int tell();
virtual int size();
};


int main() {
S(Seekable);
return 0;
}
 
B

Barry

Chameleon said:
The code is:
-----------------------------------------------
#include <cstdio>

#define S(X) printf(#X ": %d\n", sizeof(X));

class Seekable
{
public:
virtual void seek(int to, char from);
virtual int tell();
virtual int size();
};


int main() {
S(Seekable);
return 0;
}

virtual function is often implemented with v-table.
compiler inserts a v-ptr into each instance of a class with at least one
virtual function.
sizeof (v-ptr) == 4, like as ordinary pointer.
 
C

Chameleon

O/H Barry Ýãñáøå:
virtual function is often implemented with v-table.
compiler inserts a v-ptr into each instance of a class with at least one
virtual function.
sizeof (v-ptr) == 4, like as ordinary pointer.


Holy shit!
Until now, I believe whole v-table is part of class data!
It is clear now!
v-table is static data for each class declaration.
The objects have only the pointer to these static data (v-table). Not
the whole v-table.


Thanks
 
D

Default User

Chameleon said:
The code is:

You received your answer, but I'll point that the above is invalid. The
sizeof operator gives a result that is type size_t, which is an
unsigned integral type. The %d is for signed ints. size_t may or may
not even be an int.

#define S(X) printf(#X ": %d\n", (int)sizeof(X));

would work, or some variation. I didn't bother with a c++ cast, but you
could use one as well.





Brian
 
A

Aragon

You received your answer, but I'll point that the above is invalid. The
sizeof operator gives a result that is type size_t, which is an
unsigned integral type. T

Or better yet,

std::cout << "Size: " << sizeof(X) << std::endl;
 
E

eefacm

The code is:

This macro isn't safe for general use. The following example would be
very likely to cause problems:

int c = 5, d = 3;

S(c%d);

You should prefer:

#define S(X) printf("%s: %d\n", #X, static_cast<int>(sizeof(X)));

....which also reflects the comment elsewhere in this thread that
sizeof returns an unsigned type.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top