निम्नलिखित कोड पर विचार करें:शुद्ध आभासी समारोह कॉल दिलचस्प मामलों
#include <iostream>
using namespace std;
class A
{
public:
virtual void f() = 0;
A(){f();}
};
void A::f() {
cout<<"A"<<endl;
}
class B:public A{
public:
void f(){cout<<"B"<<endl;}
};
int main()
{
B b;
}
इस मामले में मैं सीधे निर्माता से आभासी फ़ंक्शन को कॉल करें और संकलक चेतावनी जो कहते हैं मिलती है:
चेतावनी: सार आभासी 'आभासी शून्य एक: : एफ() 'कन्स्ट्रक्टर से बुलाया जाता है।
लेकिन यह बिना समाप्ति और प्रिंट ए
निष्पादित करता है, तो मैं इस तरह समारोह के कॉल लपेट:
class A
{
public:
virtual void f() = 0;
A(){g();}
void g(){f();}
};
void A::f(){cout<<"A"<<endl;}
class B:public A{
public:
void f(){cout<<"B"<<endl;}
};
int main()
{
B b;
}
संकलक संकलन के दौरान नहीं उत्पादन किसी चेतावनी करता है, लेकिन यह निम्नलिखित के साथ रनटाइम पर कुचल संदेश:
pure virtual method called
terminate called without active exception
Abort
क्या कोई इन दोनों मामलों के व्यवहार की व्याख्या कर सकता है?
संकेत: http://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors – dragosht