2011-11-14 53 views
6

的大小我有一個指針Base* base_ptr到多態對象。是否有可能找出所述對象的動態類型的大小?找出一個多態對象

AFAIK,sizeof(*base_ptr) yilds靜態類型的base_ptr的大小。我開始懷疑這是不可能的,但也許我忽略了一些東西。

注:我知道,我可以一個虛函數添加到我的類型層次,它返回的大小,但這不是我的情況下,理想的解決方案。

編輯:sizeof(base_ptr) - >sizeof(*base_ptr)

+0

'的sizeof(base_ptr)'給你的大小指針,而不是任何類。 –

+0

它甚至看起來像g ++特定不提供此信息。 – aschepler

回答

11

不,你不能這樣做,在C++中 - 至少在一個可移植的方式。最好的辦法是在每個課程中實施getSize()成員函數。

5

是。您可以實現在基類返回尺寸的虛函數:

class Base 
{ 
    virtual int size() { return sizeof(Base); } 
}; 
class Derived : public Base 
{ 
    virtual int size() { return sizeof(Derived); } 
}; 

//...... 
Base* b = new Derived; 
int size = b->size(); //will call Derived::size() and return correct size