سؤال

If I create a base class pointer array, create an derived class object in a scope and pass the reference to the array and call a virtual function of the derived class in the scope correctly but outside that scope, I try calling the virtual function, it forgets it was a derived class. I tried casting it but it doesn't work.

class Base{
    public:
        Base(string str) {name = str;}
        virtual string toString() { return name;}
        Base& operator=(const Base& b) {name = b.name; return *this;}
    private:
        string name;
};
class Derived: public Base{
    public:
        Derived(string str1, string str2) {name = str1; second = str2;}
        virtual string toString() {return name + second;}
        Derived& operator=(const Derived& d) {Base::operator=(d);
                                              second = d.second; return *this;}
    private:
        string name;
        string second;
};
int main(){
    Base* baseArr[5];
    int n;
    cin >> n;
    if(n==1){
        Derived der("Derived", "Class");
        baseArr[0] = &der;
        baseArr[0]->toString() << endl; //this prints out "DerivedClass"
     }
     cout << baseArr[0]->toString(); //this prints out "Derived"
 }

Is there any way to call the derived class' function outside the scope?

هل كانت مفيدة؟

المحلول

You're invoking undefined behaviour, because you are referring to an object instance through baseArr[0] that has already been destructed. The lifetime of der does not exist past the } at the end of its scope, and you cannot refer to it through the pointer you stored after that point.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top