BlackMamba
BlackMamba

Reputation: 10252

why we should implement pure virtual function in this case?

My code:

class A
{
public:
    A(){}
    A(int _a) : a(_a){}
    virtual ~A() = 0;
private:
    int a;
};


class B : public A
{
public:
    B(){}
    B(int _a):A(_a){}
    ~B(){}
private:
};

I declare B b;, then when i compile this program, i met this error:

error LNK2019: unresolved external symbol "public: virtual __thiscall A::~A(void)" (??1A@@UAE@XZ) referenced in function "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ)

I want to know, Do we need implement the pure virtual function all the time?

Upvotes: 4

Views: 186

Answers (4)

Pete Becker
Pete Becker

Reputation: 76513

A pure virtual function must be implemented if it is called. So, for example:

struct A {
    virtual void f() = 0;
};

struct B : A {
    void f();
};

void B::f() { std::cout << "B::f called\n"; }

However, if B::f calls A::f, then A::f must be implemented:

void B::f() { A::f(); std::cout << "B::f called\n"; }

With this definition of B::f there must also be a definition of A::f.

Same thing with a virtual destructor: if it's called, it must be implemented. The thing that's different for a destructor is that the destructor in the base class is always called by the destructor for the derived class, so you must always implement a pure virtual destructor. Even if it doesn't do anything.

Upvotes: 1

spin_eight
spin_eight

Reputation: 4025

You should implement it when it is invoked. otherwise not. Pure virtual means that instance of a class that contains it coudnt be created, not that method coudnt be called, nothing prevents you from calling pure virtual method from derived class in that case - implementation is needed.

Upd: in you case, as destructor of base class is invoked - implementation is needed, see explanation above.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249642

In general you do not need to implement a pure virtual function. Indeed that's sort of the point. However, with destructors you do, because it is not acceptable for a destructor to have no implementation. This is because unlike regular virtual methods, where only the most-derived one is used at runtime, all virtual destructors in an inheritance chain are called, from the most- to the least-derived, so that all fields of a derived object may be properly destroyed.

For this reason it may be preferable to not make pure your virtual destructors, except in cases where it is necessary (i.e. when you have a base class which must be abstract but which has no other virtual methods to be made pure).

Upvotes: 9

David Brunelle
David Brunelle

Reputation: 6450

A pure virtual function is, by definition, a virtual function that needs to be define in inherited object all the time. So the answer is yes, you have. If you really have no need for it, you could just define a function with no code inside.

Upvotes: 0

Related Questions