1

Exists some differences between a constructor or destructor be virtual or not? In this case, what should be done

class A {
public:
    A();
    ~A();
}

or

class A {
public:
    virtual A();
    virtual ~A();
}

Have isocpp fot this case?

Thanks...

Lukas Man
  • 85
  • 8
  • 4
    Constructor: cannot be done. Destructor: it depends. See [*when to use virtual destructors?*](http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – juanchopanza Oct 03 '15 at 13:49

2 Answers2

1

You cannot have Virtual constructor in C++ why no virtual Constructor.

Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class. Refer to When to use Virtual Destructor.

Community
  • 1
  • 1
Lorenzo Belli
  • 1,767
  • 4
  • 25
  • 46
1

You can't have virtual constructors, but a virtual destructor makes it possible to destroy an object through a base class pointer while calling the derived destructors apropriately.

For example, dont actually run this code

class A {
public:
    A() {}
    ~A() {}
};

class B : public A {
public:
    B() {}
    virtual ~B() {}
};

class C : public B {
public:
    C() : _p( new int(0) ) {}
    ~C() { delete _p; std::cout << "Deleted p" << std::endl; }
private:
    int *_p;
};


int main() {
    C *c1 = new C();
    C *c2 = new C();

    B *bPointer = c1;
    A *aPointer = c2;

    std::cout << "Deleting through B*" << std::endl;
    delete bPointer; // "deleted p"
    std::cout << "------------" << std::endl;
    std::cout << "Deleting through A*" << std::endl;
    delete aPointer; // No output

    return 0;
}

Class A's destructor should've been marked as virtual. You only need to write virtual on the topmost class of the hierarchy.

aslg
  • 1,966
  • 2
  • 15
  • 20