sizeof() on derived class objects
Hi, here is the code
Code:
struct Base {
int mem1;
};
struct A : Base {
int mem2;
};
struct B : Base {
int mem3[10];
};
void fun(Base& base) {
cout << sizeof(base) << " ";
};
void main() {
Base base; A a; B b;
cout << sizeof(base) << " " << sizeof(a) << " " << sizeof(b) << endl;
fun(base); fun(a); fun(b);
};
the sizeof in main() worked well, but not after the object is passed into the function fun().
actually, I am trying to write a fun() that can take the base class (Base) object or any derived classes (A, B) objects and prints the correct size of the pass in object, which I failed in the above code.
Any help? Thank you very much!
Re: sizeof() on derived class objects
Quote:
Originally Posted by newHere
actually, I am trying to write a fun() that can take the base class (Base) object or any derived classes (A, B) objects and prints the correct size of the pass in object, which I failed in the above code.
sizeof is an operator whose result is determined at compile time. The object that the base reference refers to can vary at run time. As such, you are asking for the impossible (except in special cases, or possibly by overloading, which may not be quite what you want).
By the way, get rid of the semi-colons after your function definitions. Note that the global main function should return an int, not void.
Re: sizeof() on derived class objects
Quote:
Originally Posted by
laserlight
sizeof is an operator whose result is determined at compile time. The object that the base reference refers to can vary at run time. As such, you are asking for the impossible (except in special cases, or possibly by overloading, which may not be quite what you want).
Thanks! How about this
Code:
void fun(Base& base) {
A* a = dynamic_cast<A*>(&base);
if (a) {
cout << sizeof(*a);
} else {
B* b = dynamic_cast<B*>(&base);
if (b) {
cout << sizeof(*b);
} else {
cout << sizeof(base);
}
}
}
I had to make the base class virtual and this added an extra 4 bytes to my classes, which is not something that I want.
Re: sizeof() on derived class objects
Why do you care about the size of your object? I've been doing this a long time and that's never come up for me.
Re: sizeof() on derived class objects
it's not very maintainable - everytime you add a derived class you need to remember this function and add in another else if
Re: sizeof() on derived class objects
Quote:
Originally Posted by newHere
How about this
If you are going to do that, you should just overload fun instead.
Quote:
Originally Posted by GCDEF
Why do you care about the size of your object? I've been doing this a long time and that's never come up for me.
With few exceptions, same here.
Re: sizeof() on derived class objects
Size matters :P
Guess theres no way out. Cheese mates.
Re: sizeof() on derived class objects
Quote:
Originally Posted by newHere
Size matters
Yoda disagrees :p