I find this strange. In the ctor of Sample_Base, I call bar() which internally calls fun() which is a pure virtual function. I get the error "pure virtual function" called. Which is fine. Now, if I call fun() directly from Sample_Base's ctor, I don't get that error. I tried it on VC++ 2010 Beta 2 and on g++ 4.4.1 on Ubuntu 9.10. I agree that giving an implementation for pure virtual function, other than pure virtual destructor, is meaningless. But, I am a bit surprised about this behaviour.
class Sample_Base
{
public:
Sample_Base()
{
bar();
// fun();
}
/* This is code does not throw any error.
Sample_Base()
{
fun();
}
*/
void bar()
{
fun();
}
virtual void fun() = 0;
virtual ~Sample_Base();
};
Sample_Base::~Sample_Base()
{
}
void Sample_Base::fun()
{
std::cout << "Sample_Base::fun\n";
}
class Sample_Derived : public Sample_Base
{
public:
Sample_Derived() : Sample_Base()
{
fun();
}
void fun()
{
std::cout << "Sample_Derived::fun\n";
}
~Sample_Derived()
{
}
};
When you call the function directly, since you are in the constructor, the compiler resolves the static type of your object (Sample_Base) and calls Sample_Base::fun() directly. Since you provided an implementation for it, the compiler finds the function and it works.
When you call it indirectly, through bar(), the compiler must use the dynamic type, so it does a virtual call that gets resolved at runtime. And there it fails, because it calls a pure virtual function.
So the difference is in the moment it binds the function to the call.
Providing a definition for a pure virtual function is not necessarily meaningless. Marking a virtual function pure means that the enclosing class is abstract and that any class that derives from it is abstract unless the final override for that function is not a pure virtual function. A pure virtual function can still be called via an explicit non-virtual call.
In the body of a base class constructor (but not from a ctor-initializer) the version of a virtual function called through a virtual call is one defined in the class itself or one of its bases and not of any class overriding it (which would not yet have been constructed). This is specified explicitly in 12.7 [class.cdtor]/3.
It is legal to call a pure virtual function explicitly in a constructor body (i.e. using an explicit class qualifier) - although this would required the function to have a body defined - but it is undefined behaviour to call a pure virtual function via a virtual call which is only possible from the constructor or destructor of an abstract class. This is specified explicitly in 10.4 [class.abstract]/6.
At construction time, when the Sample_Base constructor is called, the object is not fully constructed yet. Specifically the parts belonging to Sample_Derived are not yet created calls to virtual functions that would be overwritten by Sample_Derived will not call the implementation in Sample_Derived, but the version defined in Sample_Base. And since the function has no implementation there you get an error.
For more information and possible workarounds also see this entry in the C++ FAQ Lite.
Calling a virtual function won't call the overriding functions in the derived classes. Calling a pure virtual function in a constructor or destructor is Undefined behavior.
You might be interested in reading this and this.
This behavior is not undefined, it's explicitly defined: virtual functions are not virtual in constructors and destructors. They call the static version of the function. If the function is pure virtual, this results in the famous "pure virtual call" error in VC.
I've seen an amusing variation of this in a multithreaded program: an object is being destructed on thread A, while thread B is attempting to call a virtual function. There was no virtual function call in the constructor or destructor, but we still got hit with a pure virtual call error.
Related
This question already has answers here:
Pure virtual function with implementation
(10 answers)
Closed 3 years ago.
Pure virtual functions (when we set = 0) can also have a function body.
What is the use to provide a function body for pure virtual functions, if they are not going to be called at all?
Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called dynamically, through a virtual dispatch mechanism. Yet, this very same function can easily be called statically, non-virtually, directly (without virtual dispatch).
In C++ language a non-virtual call to a virtual function is performed when a qualified name of the function is used in the call, i.e. when the function name specified in the call has the <class name>::<function name> form.
For example
struct S
{
virtual void foo() = 0;
};
void S::foo()
{
// body for pure virtual function `S::foo`
}
struct D : S
{
void foo()
{
S::foo();
// Non-virtual call to `S::foo` from derived class
this->S::foo();
// Alternative syntax to perform the same non-virtual call
// to `S::foo` from derived class
}
};
int main()
{
D d;
d.S::foo();
// Another non-virtual call to `S::foo`
}
"Effective C++" Meyers mentions a
reason for a pure virtual function to
have a body: Derived classes that
implement this pure virtual function
may call this implementation smwhere
in their code. If part of the code of
two different derived classes is
similar then it makes sense to move it
up in the hierarchy, even if the
function should be pure virtual.
see here.
For most pure virtual functions, you'd be right. However, for a pure virtual destructor, it's actually important to define a corresponding destructor implementation:
The "pure virtual" is to require derived classes to implement their destructor.
Your base class destructor implementation is so that the derived class destructors can successfully "chain up" afterwards.
I'm having trouble understanding what's the reason for the crash in the following code :
class A {
public:
virtual ~A() { goo(); }
void goo() { absFoo(); }
virtual void absFoo() = 0;
};
class B : public A {
public:
void absFoo() { cout << "In B \n"; }
};
int main()
{
B b1;
b1.goo();
}
The main prints "In B" as expected, but in the end when it crashes, I can't debug it either, the compiler pops a weird message.
So my question is, when the destructor of A calls "goo()", does "absFoo()", crash
because we're referring to an abstract function?
Or does the compiler actually look for a definition in the derived classes? (And it doesn't exist anymore because it was destructed beforehand so it crashes)
I know that if we had called "absFoo()" directly from the destructor, the reason would have been the abstract function. But since here it's an outside function calling "absFoo()" I'm having trouble understanding the real reason.
What happens when a destructor calls an abstract function
First, let us consider what happens when a destructor calls any virtual function (the same applies to the constructor by the way): When a virtual function foo is called in the destructor of T, the call will not be dispatched dynamically to an implementation in a derived type (the lifetime of any derived object has already ended), but statically to the implementation T::foo.
If T::foo is pure virtual, then calling it without dynamic dispatch will have undefined behaviour. That is what happens when a pure virtual function is (indirectly) called in a destructor (or constructor).
Just to complement the already accepted answer, this is the documentation from cppreference.
When a virtual function is called directly or indirectly from a
constructor or from a destructor (including during the construction or
destruction of the class’s non-static data members, e.g. in a member
initializer list), and the object to which the call applies is the
object under construction or destruction, the function called is the
final overrider in the constructor’s or destructor’s class and not one
overriding it in a more-derived class.
In other words, during construction or destruction, the more-derived classes do not exist.
As the object is deconstructed, the vtable is updated to match the new status of the object.
Since you've removed the last function, the compiler will do whatever it considers fit; which in the case of a debug compilation in visual studio, will fallback to an abort reporting that a pure virtual function was called.
The vtable however is not part of the standard, it's an implementation detail, and there's no requirement for your program to crash; it's just what is considered the nicest thing to do when you've called a pure virtual function.
Consider the following code:
#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;
}
In this case I directly call the virtual function from constructor and get compiler warning which says:
warning: abstract virtual 'virtual void A::f()' called from constructor.
But it executes without termination and prints A.
If I wrap the call of the function like this:
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;
}
The compiler does not output any warning during compilation but it crushes at runtime with the following message:
pure virtual method called
terminate called without active exception
Abort
Can anybody explain the behavior of both of this cases?
§ 10.4 Abstract classes [class.abstract] / p6
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.
In brief: The effect of making a call to a pure virtual function directly or indirectly for the object being created from constructor is undefined.
A call to pure virtual member functions cannot be used from a constructor or a destructor, no matter if the call is direct or indirect, because then you end up with an undefined behavior.
The only useful example of providing the implementation of a pure virtual function is when calling it from a derived class:
struct A
{
virtual void f() = 0;
};
void A::f()
{
cout<<"A"<<endl;
}
struct B : A
{
void f()
{
A::f();
cout<<"B"<<endl;
}
};
In the first case, the compiler happens to save you by statically dispatching to A::f(), since it knows the static type of A. But it's quite right that this is horribly undefined behaviour and you shouldn't do it.
In the second case, the compiler does not statically dispatch to A::f() since the call is not in the constructor so it must dynamically dispatch it. Different ABIs handle pure virtual calls differently, but both MSVC and Itanium have a dedicated pure virtual call handler which is placed in the vtable to catch these events. This is what produces the error message you see.
From a compiler's point of view, if you look at how the function f() is invoked:
Case-1: A's ctor calls A-ctor => f() directly. Compiler knows precisely that this is the case and decides to issue a warning.
Case-2: A's ctor calls A-ctor => g() => f(). There are entirely legitimate cases of calling f() from one of the class methods. Compiler can not say that this is illegal. The callgraph could have been from * => bar() => g() -> f(), meaning the type of the object is not known. Such paths being possible, makes dynamic dispatching necessary - leading to the runtime error.
As others pointed out, this is undefined usage and compilers only go so far in detecting and warning.
Undefined behaviour means that the compiler does not have to handle the situation in any particularly defined manner.
Here your compiler, that knew the actual type of A in its constructor was able to inline in the pure virtual method rather than call it through the v-table. This is what would happen if the method were normal virtual, not pure virtual, and this would be defined behaviour.
Whilst it would be the behaviour too even via g(), the compiler did not do this for a pure virtual f() function. It doesn't have to.
The simple moral is do not invoke undefined behaviour, and if you want to call f() from the constructor do not make it pure virtual.
If you want to enforce your sub-classes to implement f(), do not call it from the constructor of A but give that function you want to call a different name. Preferably not virtual at all.
I have two questions and the answers I found here didn't totally satisfy me:
Why declaring a constructor as virtual is meaningless?
What happens when I call a virtual function from a constructor? Is the virtual table used too?
Why declaring a constructor as virtual is meaningless?
Before the constructor is executed, the object does not exists, so there is no such thing as an override.
What happens when I call a virtual function from a constructor? Is the virtual table used too?
It can. In most cases, if the call is directly performed from the constructor the compiler can skip the dynamic dispatch, as it knows what the final overrider is at this point. But it need not perform that optimization, and even if it can do that in the constructor directly, it cannot do it if you call a non-virtual function that in turn calls the virtual function. Because the non-virtual function might be called for objects of derived types it must use the virtual dispatch mechanism.
When calling a constructor, the actual type of the (not yet existing) object is known for very sure. So calling a constructor will never be indirect. (Only virtual functions are called indirectly when called via a pointer / reference.)
BaseClass *x = new SubClass();
Calling a virtual function in a constructor doesn't do what you might expect. As the subclass hasn't been initialized yet, the virtual function on the final class can't be called (the v-table currently points to the class of the constructor currently being executed).
class BaseClass {
BaseClass() {
call();
}
virtual void call() {
std::cout << "BaseClass!";
}
};
class SubClass : public BaseClass {
SubClass() : BaseClass()
{
}
void call() {
std::cout << "SubClass!";
}
};
http://ideone.com/9aQVIc
Why declaring a constructor as virtual is meaningless.
When the constructor is invoked the virtual table would not be available in the memory. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you can not be creating a sub-class of the class you must be creating the class so there would never be any need to declare a constructor virtual. Therefore, there is no such a thing as virtual constructor in C++.
What happens when I call a virtual function from a constructor? Is the virtual table used too
See C++ FAQ link about detailed explanation of this question.
From 10.4 Abstract Classes parag. 6 in the Standard :
"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."
Assuming that a call to a non-pure virtual function from a constructor (or destructor), is allowed by the Standard, why the difference ?
[EDIT] More standards quotes about pure virtual functions:
§ 10.4/2 A virtual function is specified pure by using a pure-specifier (9.2) in the function declaration in the class definition. A pure virtual function needs be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1). ... [ Note: A function declaration cannot provide both a pure-specifier and a definition —end note ]
§ 12.4/9 A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined.
Some questions that need answering are:
Where the pure virtual function has not been given an implementation, should this not be a compiler or linker error instead?
Where the pure virtual function has been given an implementation, why can it not be well-defined in this case to invoke this function?
Because a virtual call can NEVER call a pure virtual function -- the only way to call a pure virtual function is with an explicit (qualified) call.
Now outside of constructors or destructors, this is enforced by the fact that you can never actually have objects of an abstract class. You must instead have an object of some non-abstract derived class which overrides the pure virtual function (if it didn't override it, the class would be abstract). While a constructor or destructor is running, however, you might have an object of an intermediate state. But since the standard says that trying to call a pure virtual function virtually in this state results in undefined behavior, the compiler is free to not have to special case things to get it right, giving much more flexibility for implementing pure virtual functions. In particular, the compiler is free to implement pure virtuals the same way it implements non-pure virtuals (no special case needed), and crash or otherwise fail if you call the pure virtual from a ctor/dtor.
I think this code is an example of the undefined behaviour referenced by the standard. In particular, it is not easy for the compiler to notice that this is undefined.
(BTW, when I say 'compiler', I really mean 'compiler and linker'. Apologies for any confusion.)
struct Abstract {
virtual void pure() = 0;
virtual void foo() {
pure();
}
Abstract() {
foo();
}
~Abstract() {
foo();
}
};
struct X : public Abstract {
virtual void pure() { cout << " X :: pure() " << endl; }
virtual void impure() { cout << " X :: impure() " << endl; }
};
int main() {
X x;
}
If the constructor of Abstract directly called pure(), this would obviously be a problem and a compiler can easily see that there is no Abstract::pure() to be called, and g++ gives a warning. But in this example, the constructor calls foo(), and foo() is a non-pure virtual function. Therefore, there is no straightforward basis for the compiler or linker to give a warning or error.
As onlookers, we can see that foo is a problem if called from the constructor of Abstract. Abstract::foo() itself is defined, but it tries to call Abstract::pure and this doesn't exist.
At this stage, you might think that the compiler should issue a warning/error about foo on the grounds that it calls a pure virtual function. But instead you should consider the derived non-abstract class where pure has been given an implementation. If you call foo on that class after construction (and assuming you haven't overriden foo), then you will get well-defined behaviour. So again, there is no basis for a warning about foo. foo is well-defined as long as it isn't called in the constructor of Abstract.
Therefore, each method (the constructor and foo) are each relatively OK if you look on them on their own. The only reason we know there is a problem is because we can see the big picture. A very smart compiler would put each particular implementation/non-implementation into one of three categories:
Fully-defined: It, and all the methods it calls are fully-defined at every level in the object hierarchy
Defined-after-construction. A function like foo that has an implementation but which might backfire depending on the status of the methods it calls.
Pure virtual.
It's a lot of work to expect a compiler and linker to track all this, and hence the standard allows compilers to compile it cleanly but give undefined behaviour.
(I haven't mentioned the fact that it is possible to give implementations to pure-virtual methods. This is new to me. Is it defined properly, or is it just a compiler-specific extension? void Abstract :: pure() { })
So, it's not merely undefined 'because the standard says so`. You have to ask yourself 'what behaviour would you define for the above code?'. The only sensible answer is either to leave it undefined or to mandate a run-time error. The compiler and linker won't find it easy to analyse all these dependencies.
And to make matters worse, consider pointers-to-member-functions! The compiler or linker can't really tell if the 'problematic' methods will ever be called - it might depend on a whole load of other things that happen at runtime. If the compiler sees (this->*mem_fun)() in the constructor, it can't be expected to know how well-defined mem_fun is.
It is the way the classes are constructed and destructed.
Base is first constructed, then Derived. So in the constructor of Base, Derived has not yet been created. Therefore none of its member functions can be called. So if the constructor of Base calls a virtual function, it can't be the implementation from Derived, it must be the one from Base. But the function in Base is pure virtual and there is nothing to call.
In destruction, first Derived is destroyed, then Base. So once again in the destructor of Base there is no object of Derived to invoke the function, only Base.
Incidentally it is only undefined where the function is still pure virtual. So this is well-defined:
struct Base
{
virtual ~Base() { /* calling foo here would be undefined */}
virtual void foo() = 0;
};
struct Derived : public Base
{
~Derived() { foo(); }
virtual void foo() { }
};
The discussion has moved on to suggest alternatives that:
It might produce a compiler error, just like trying to create an instance of an abstract class does.
The example code would no doubt be something like:
class Base
{
// other stuff
virtual void init() = 0;
virtual void cleanup() = 0;
};
Base::Base()
{
init(); // pure virtual function
}
Base::~Base()
{
cleanup(); // which is a pure virtual function. You can't do that! shouts the compiler.
}
Here it is clear what you are doing is going to get you into trouble. A good compiler might issue a warning.
it might produce a link error
The alternative is to look for a definition of Base::init() and Base::cleanup() and invoke that if it exists, otherwise invoke a link error, i.e. treat cleanup as non-virtual for the purpose of constructors and destructors.
The issue is that won't work if you have a non-virtual function calling the virtual function.
class Base
{
void init();
void cleanup();
// other stuff. Assume access given as appropriate in examples
virtual ~Base();
virtual void doinit() = 0;
virtual void docleanup() = 0;
};
Base::Base()
{
init(); // non-virtual function
}
Base::~Base()
{
cleanup();
}
void Base::init()
{
doinit();
}
void Base::cleanup()
{
docleanup();
}
This situation looks to me to be beyond the capability of both the compiler and linker. Remember that these definitions could be in any compilation unit. There is nothing illegal about the constructor and destructor calling init() or cleanup() here unless you know what they are going to do, and there is nothing illegal about init() and cleanup() calling the pure virtual functions unless you know from where they are invoked.
It is totally impossible for the compiler or linker to do this.
Therefore the standard must allow the compile and link and mark this as "undefined behaviour".
Of course if an implementation does exist, the compiler is free to use it if able. Undefined behaviour doesn't mean it has to crash. Just that the standard doesn't say it has to use it.
Note that this case the destructor is calling a member function that calls the pure virtual but how do you know it will do even this? It could be calling something in a completely different library that invokes the pure virtual function (assume access is there).
Base::~Base()
{
someCollection.removeMe( this );
}
void CollectionType::removeMe( Base* base )
{
base->cleanup(); // ouch
}
If CollectionType exists in a totally different library there is no way any link error can occur here. The simple matter is again that the combination of these calls is bad (but neither one individually is faulty). If removeMe is going to be calling pure-virtual cleanup() it cannot be called from Base's destructor, and vice-versa.
One final thing you have to remember about Base::init() and Base::cleanup() here is that even if they have implementations, they are never called through the virtual function mechanism (v-table). They would only ever be called explicitly (using full class-name qualification) which means that in reality they are not really virtual. That you are allowed to give them implementations is perhaps misleading, probably wasn't really a good idea and if you wanted such a function that could be called through derived classes, perhaps it is better being protected and non-virtual.
Essentially: if you want the function to have the behaviour of a non-pure virtual function, such that you give it an implementation and it gets called in the constructor and destructor phase, then don't define it as pure virtual. Why define it as something you don't want it to be?
If all you want to do is prevent instances being created you can do that in other ways, such as:
- Make the destructor pure virtual.
- Make the constructors all protected
Before discussing why it's undefined, let's first clarify what the question is about.
#include<iostream>
using namespace std;
struct Abstract {
virtual void pure() = 0;
virtual void impure() { cout << " Abstract :: impure() " << endl; }
Abstract() {
impure();
// pure(); // would be undefined
}
~Abstract() {
impure();
// pure(); // would be undefined
}
};
struct X : public Abstract {
virtual void pure() { cout << " X :: pure() " << endl; }
virtual void impure() { cout << " X :: impure() " << endl; }
};
int main() {
X x;
x.pure();
x.impure();
}
The output of this is:
Abstract :: impure() // called while x is being constructed
X :: pure() // x.pure();
X :: impure() // x.impure();
Abstract :: impure() // called while x is being destructed.
The second and third lines are easy to understand; the methods were originally defined in Abstract, but the overrides in X take over. This result would have been the same even if x had been a reference or pointer of Abstract type instead of X type.
But this interesting thing is what happens inside the constructor and destructor of X. The call to impure() in the constructor calls Abstract::impure(), not X::impure(), even though the object being constructed is of type X. The same happens in the destructor.
When an object of type X is being constructed, the first thing that is constructed is merely an Abstract object and, crucially, it is ignorant of the fact that it will ultimately be an X object. The same process happens in reverse for the destruction.
Now, assuming you understand that, it is clear why the behaviour must be undefined. There is no method Abstract :: pure which could be called by the constructor or destructor, and hence it wouldn't be meaningful to try to define this behaviour (except possibly as a compilation error.)
Update: I've just discovered that is possible to give an implementation, in the virtual class, of a pure virtual method. The question is: Is this meaningful?
struct Abstract {
virtual void pure() = 0;
};
void Abstract :: pure() { cout << "How can I be called?!" << endl; }
There will never be an object whose dynamic type is Abstract, hence you'll never be able to execute this code with a normal call to abs.pure(); or anything like that. So, what is the point of allowing such a definition?
See this demo. The compiler gives warnings, but now the Abstract::pure() method is callable from the constructor. This is the only route by which Abstract::pure() can be called.
But, this is technically undefined. Another compiler is entitled to ignore the implementation of Abstract::pure, or even to do other crazy things. I'm not aware of why this isn't defined - but I wrote this up to try to help clear up the question.