Junior — Senior
How do virtual functions and destructors affect the order of output when deleting through a base class pointer
livecode
Task condition
Question: What set of strings will be output by the program, considering the behavior of virtual functions, the sequence of constructor and destructor calls, and the behavior when deleting an object through a base class pointer.
# include <iostream>
struct Base {
Base() { print(); }
virtual void print() { std::cout << "Base" << std::endl; }
virtual ~Base() { print(); }
};
struct Derived : Base {
Derived() { print(); }
virtual void print() { std::cout << "Derived" << std::endl; }
virtual ~Derived() { print(); }
};
int main(int argc, char** argv) {
Base* ptr = new Derived();
ptr->print();
delete ptr;
}
Analyze how the call to print occurs in the base class constructor, how the method is overridden in the derived class, and which functions will be executed when destroying the object, especially when deletion occurs through a base class pointer.