嗷嗷按,今天被问到在constructor/destructor中调用virtual member function的问题。答错了,很羞耻。 依稀记得在constructor/destructor调用virtual member function不好,就随口答道不能调用,可能会出错。 后来仔细想想不对,羞耻呀。调用是可以的,从语言角度没错,只不过和其他情况下调用虚函数有些不同。 看代码: classA ...
constructor执行的时候对象都还没有,如何virtual?destructor不一定要virtual。
Describe each case separately. I assume you're both far from being diligent students. You have no idea when the class constructor and destructor are called. Besides, you missed the lesson "In what order to determine objects of parent classes when you determine a parent, and in what order to...
This code fragment always returns 1 in the first case. He could use inline to speed up the constructor and the destructor. It doesn't matter to the compiler anyway. The result of the function is never used, the function doesn't use any external arguments — the compiler will just throw ...
在线看Advanced C++ 5: Virtual Function in Constructor.. 4分钟 59秒。31 1月 2017的高清视频,VK免费视频库免注册! 244 — 已浏览。 1 — 已评价。
cout << "Derived Constructor \n" ; } ~Derived() { cout << "Derived Destructor \n" ; } private: string str; }; int main() { Base *pB = new Derived("derived"); delete pB; } Output from the run is: Base Constructor Derived Constructor ...
The prototype of virtual functions must match both the base and derived classes for proper overriding. Overriding a virtual function in derived classes is optional; otherwise, the base class’s version is used. While a class can have a virtual destructor, a virtual constructor is not permitted ...
//Base.h #pragma once #include <iostream> using namespace std; class Base { public: Base() { cout << "Base : constructor" << endl; log(); } virtual ~Base() { cout<<"Base : destructor" << endl; } virtual void log() const = 0; }; C++ Copy //Base.cpp #include ...
Behavior during construction and destruction[edit] Languages differ in their behavior while the constructor or destructor of an object is running. For some languages, notably C++, the virtual dispatching mechanism has different semantics during construction and destruction of an object. While it is reco...
Reports virtual member function calls from constructors or destructors. Since construction starts with the base class and moves to the derived classes, the resources of the derived class are not yet initialized. Destruction is performed in reverse order, so calling a virtual function can lead to ...