Is it possible to change a C++ object's class after instantiation?

后端 未结 16 1835
忘掉有多难
忘掉有多难 2021-02-02 06:50

I have a bunch of classes which all inherit the same attributes from a common base class. The base class implements some virtual functions that work in general cases, whilst eac

16条回答
  •  名媛妹妹
    2021-02-02 06:57

    you cannot change to the type of an object after instantiation, as you can see in your example you have a pointer to a Base class (of type base class) so this type is stuck to it until the end.

    • the base pointer can point to upper or down object doesn't mean changed its type:

      Base* ptrBase; // pointer to base class (type)
      ptrBase = new Derived; // pointer of type base class `points to an object of derived class`
      
      Base theBase;
      ptrBase = &theBase; // not *ptrBase = theDerived: Base of type Base class points to base Object.
      
    • pointers are much strong, flexible, powerful as much dangerous so you should handle them cautiously.

    in your example I can write:

    Base* object; // pointer to base class just declared to point to garbage
    Base bObject; // object of class Base
    *object = bObject; // as you did in your code
    

    above it's a disaster assigning value to un-allocated pointer. the program will crash.

    in your example you escaped the crash through the memory which was allocated at first:

    object = new Derived;
    

    it's never good idea to assign a value and not address of a subclass object to base class. however in built-in you can but consider this example:

    int* pInt = NULL;
    
    int* ptrC = new int[1];
    ptrC[0] = 1;
    
    pInt = ptrC;
    
    for(int i = 0; i < 1; i++)
        cout << pInt[i] << ", ";
    cout << endl;
    
    int* ptrD = new int[3];
    ptrD[0] = 5;
    ptrD[1] = 7;
    ptrD[2] = 77;
    
    *pInt = *ptrD; // copying values of ptrD to a pointer which point to an array of only one element!
    // the correct way:
    // pInt = ptrD;
    
    for(int i = 0; i < 3; i++)
        cout << pInt[i] << ", ";
    cout << endl;
    

    so the result as not as you guess.

提交回复
热议问题