Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ temporary - "pure virtual method called"

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?

like image 877
Dave Avatar asked Jan 23 '13 22:01

Dave


People also ask

What is the pure virtual function called?

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.

Why is virtual method called virtual?

'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.

What is meant by virtual method?

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#.

Is pure virtual function polymorphism?

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.


1 Answers

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>.

like image 55
Seth Carnegie Avatar answered Sep 20 '22 10:09

Seth Carnegie