problem with sizeof() function

Hello guys. i have a weird problem whenever i try to use this function with a class that is derived from a parent class.

Subclass base

sizeof(Subclass));

the problem i get is that i the sizeof function returns the size of the parent class instead of the class that i enter into the function. I think that its bc it calls the constructor for the parent class first and so it returns the size of that instead of the size of "Subclass". is there any way around this problem.
plz guys. i really need to figure this out for my school end of semester project
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

class Base {
	int a;
};

class Derived: public Base {
	int b;
};

int main() {
	Base& inst = *(new Derived());
	std::cout << "Base: " << sizeof(Base) << ", Derived: " << sizeof(Derived) << "\n";
	std::cout << "Inst: " << sizeof(inst) << "\n";
	return 0;
}


Are you doing something like that and expecting to get sizeof(inst) == sizeof(Derived)?

If so you're using sizeof wrong. sizeof gets the size of the type of the expression you give it, you should never call sizeof on an instance for the very reason of confusing what you may be. You should only call it on a class, as it only ever gets the size of classes, not instances.

You'll need to implement a virtual member of your class if you want to find out the size of a given instance when all you have is a reference to the base class, like so:

1
2
3
4
5
6
7
8
9
10
11
class Base {
	virtual size_t getSize() {
		return sizeof(Base);
	}
};

class Derived: public Base {
	size_t getSize() {
		return sizeof(Derived);
	}
};


Although I highly doubt that's the best way if doing what you're trying to do, you may want to rethink the problem.
Topic archived. No new replies allowed.