Thread: Virtual & Pure virtual destructors

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    I don't know why you said the code crashes (do you mean it won't compile or you get a runtime explosion?), it compiled/ran okay for me.

    A pure virtual function (it can be any function, doesn't have to be the destructor) is a function that declares that you can not instantiate an object of that type. In other words, you declare a pure virtual function in a class that is strictly intended to be inherited and not used itself. The way you make a function pure virtual is to make it virtual and after the declaration add "= 0" In addition, if you inherit from such a base class, you are required to override the pure virtual function. BTW, this is what's referred to as an 'abstract base class'
    For example:
    Code:
    class BaseShape {
    public:
      virtual int GetArea() = 0;//this function is pure virtual
    };
    
    class Square : public BaseShape {
    public:
      virtual int GetArea() { return 100; }//function must be defined
    };
    
    class Triangle : public BaseShape {
    public:
      virtual int GetArea() { return 100; }//function must be defined
    };
    
    int main() {
      //BaseShape bs;//this line won't compile. can't instantiate it!
      Square *sq = new Square;
      delete sq;
    
      return 0;
    }
    The reason you should make destructors virtual when they are being inherited from is that if you don't, destructors might not be called (depending on usage).
    For example:
    Code:
    class A {
    public:
      virtual ~A() { cout << "A\n"; }
    };
    
    class B {
    public:
      ~B() { cout << "B\n"; }
    };
    
    int main() {
      A *pA = new B;
      delete pA;
      
      return 0;
    If class A's destructor wasn't virtual, ~B() would not be called upon destruction.

    HTH
    Last edited by LuckY; 08-21-2002 at 12:04 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-28-2009, 09:25 AM
  2. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  3. Information Regarding Pure Virtual Functions
    By shiv_tech_quest in forum C++ Programming
    Replies: 6
    Last Post: 01-29-2003, 04:43 AM
  4. C++ XML Class
    By edwardtisdale in forum C++ Programming
    Replies: 0
    Last Post: 12-10-2001, 11:14 PM
  5. virtual or pure virtual
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 12-01-2001, 07:19 PM