sizeof operator

D

dharmesh Gupta

Hi All,

the following program gives out put as

4 1

but i am unable to understand it , coulf anyone help me out

Thanks
Dharmesh
//////////////////////////////////////////
#include <stdio.h>

class x
{
public:
virtual fn1();
};

class y
{
public:
fn1();
};

void main()
{
int a,b;
a = sizeof(x);
b = sizeof(y);
printf("%d\t %d ",a,b);
}
/////////////////////////////////////////////////////////
 
P

Peter van Merkerk

dharmesh Gupta said:
Hi All,

the following program gives out put as

4 1

but i am unable to understand it , coulf anyone help me out

Thanks
Dharmesh
//////////////////////////////////////////
#include <stdio.h>

class x
{
public:
virtual fn1();
};

class y
{
public:
fn1();
};

void main()
{
int a,b;
a = sizeof(x);
b = sizeof(y);
printf("%d\t %d ",a,b);
}
/////////////////////////////////////////////////////////

Class x has a virtual function; as a result instances of class x will have
a (hidden) vtable pointer to implement the virtual function call mechanism
with many compilers. A compiler may choose to implement the virtual
function call mechanism differently, but the vtable mechanism is used by
many C++ compilers. On many platforms (including yours) the size of the
vtable pointer is 4 bytes.

Class y doesn't have virtual functions and doesn't have member functions.
So instances of class y don't need to occupy memory. However the C++
standard dictates that the sizeof() operator should yield a value greater
than 0 for most derived classes; this explains why sizeof(y) produces 1
instead of 0.
 
R

Ralf

In the first case your type has an implicit member. The vtable pointer which
has the size of 4 bytes.
In the second case there is no member inside the class. The definition in
C++ is that a type has the
minimum size of one byte.


Ralf

www.oop-trainer.de
 

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

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,405
Latest member
DavidCex

Latest Threads

Top