티스토리 뷰


테스트 코드
// Has been tested with Dev-C++(GCC 4.X)

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;


class BaseClass {
public:
      string name;
      virtual void print() { cout << name << endl; }
      
};

class Class : public BaseClass {
public:
      string familyName;
      void print() { cout << name << " " << familyName<< endl; }

};

int main(int argc, char *argv[])
{
    

    const int numElem = 3;
    Class clsArray[3];
    clsArray[0].name = "David";
    clsArray[0].familyName = "Robinson";
    
    clsArray[1].name = "Daewon";
    clsArray[1].familyName = "Lee";
    
    clsArray[2].name = "Charlie";
    clsArray[2].familyName = "Chaplin";
    
    BaseClass* bsClsArray = clsArray;


    // Runtime error occurs after processing first element of bsClsArray,
    //   because bsClsArray[i] is performed with bsClsArray + sizeof(BaseClass)
    //   not with bsClsArray + sizeof(Class)
    
    // We can get fine result by replacing BaseClass* with Class* 
    //   in declaration of bsClsArray
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
댓글