As I understand temporaries, the following code should work, but it doesn't.
struct base
{
virtual~base() {}
virtual void virt()const=0;
};
struct derived:public base
{
virtual void virt()const {}
};
const base& foo() {return derived();}
int main()
{
foo().virt();
return 0;
}
The call to virt() gives a "pure virtual function called" error. Why is that, and what should I do?
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
'virtual function' means a member function where the specific implementation will depend on the type of the object it is called upon, at run-time. The compiler and run-time support of the language contrive to make this happen. The keyword 'virtual' in C++ was taken from Simula, which had impressed Bjarne Stroustrup.
A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.
A pure virtual function (or abstract function) in C++ is a virtual function for which we don't have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration. These are the concepts of Run-time polymorphism.
You're returning a reference to a temporary which is destructed when the function ends at the end of the return
statement and you get undefined behaviour.
You cannot return any kind of reference to a temporary and if you return a base
by value you'll get slicing, so if you really want this to work, you should return a std::unique_ptr<base>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With