A Bug in the land of construction???
-
/* ** This is an interesting C++ bug, well I think it is a bug */ class CTest1 { public: BYTE* pbData; public: CTest1() { pbData = new BYTE[GetDataSize()]; } virtual int GetDataSize() { return 16; } }; class CTest2 : public CTest1 { CTest2() : CTest1() { } virtual int GetDataSize() { return 32; } }; /* ** when CTest2 is created you would expect a buffer of 32 bytes to be allocated ** but lo and behold, you get 16, try it ** ** in c# they got it right, try the same experiment and you will get 32 allocated in CTest2 */ public class CTest1 { public byte[] abyData = null; public CTest1() { abyData = new byte[DataSize]; } virtual int DataSize { get{return 16;} } } public class CTest2 : CTest1 { override int DataSize { get{return 32;} } }
-
/* ** This is an interesting C++ bug, well I think it is a bug */ class CTest1 { public: BYTE* pbData; public: CTest1() { pbData = new BYTE[GetDataSize()]; } virtual int GetDataSize() { return 16; } }; class CTest2 : public CTest1 { CTest2() : CTest1() { } virtual int GetDataSize() { return 32; } }; /* ** when CTest2 is created you would expect a buffer of 32 bytes to be allocated ** but lo and behold, you get 16, try it ** ** in c# they got it right, try the same experiment and you will get 32 allocated in CTest2 */ public class CTest1 { public byte[] abyData = null; public CTest1() { abyData = new byte[DataSize]; } virtual int DataSize { get{return 16;} } } public class CTest2 : CTest1 { override int DataSize { get{return 32;} } }
Vtable initiazation takes place in constructor of base class,its obvious that base class function will get called
-
/* ** This is an interesting C++ bug, well I think it is a bug */ class CTest1 { public: BYTE* pbData; public: CTest1() { pbData = new BYTE[GetDataSize()]; } virtual int GetDataSize() { return 16; } }; class CTest2 : public CTest1 { CTest2() : CTest1() { } virtual int GetDataSize() { return 32; } }; /* ** when CTest2 is created you would expect a buffer of 32 bytes to be allocated ** but lo and behold, you get 16, try it ** ** in c# they got it right, try the same experiment and you will get 32 allocated in CTest2 */ public class CTest1 { public byte[] abyData = null; public CTest1() { abyData = new byte[DataSize]; } virtual int DataSize { get{return 16;} } } public class CTest2 : CTest1 { override int DataSize { get{return 32;} } }
Simply, C++ has a different order of construction than C# or Java. It was a design decision, not a bug. Take a look at this article[^] for more details.
My programming blahblahblah blog. If you ever find anything useful here, please let me know to remove it.