samedi 27 juin 2015

Understanding pure-virtual functions

The following code compiles fine:

struct A
{
    const int a;
    virtual void foo() = 0;
};

struct B : A{ };

void A::foo(){ std::cout << "foo" << std::endl; }

DEMO

The thing is the struct A is an abstract therefore we can't instanciate it. But we can subclass it and

struct A
{
    const int a;
    virtual void foo() = 0;
};

struct B : A{ };

void A::foo(){ std::cout << "foo" << std::endl; }

int main(int argc, char ** argv)
{
    B b;
    b.foo(); //error: implement pure-virtual
}

DEMO

still can't use the A's implementation of foo and I suspect it will never called. So, I have no idea about application of such definition... Yes, it's useful to provide a definition for a virtual destructors, but that's not the case.

Where the definition of pure-virtuals can be used?

Aucun commentaire:

Enregistrer un commentaire