1

Possible Duplicate:
Pure virtual destructor in C++

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

class B:public A{
        int *i;
    public:
        ~B() {delete i;}
};

int main(){
    B* temp = new B;
}

I'm just trying to have B be an implementation of A. For some reason I cannot do this.

Community
  • 1
  • 1
user1202422
  • 558
  • 2
  • 8
  • 16

2 Answers2

3

In C++ destructor can be pure virtual:

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

But in every case it needs to be implemented:

inline A::~A() {} 

Otherwise A is not usable class. I mean destruction of derived (S/B) is not possible. And possibility of destruction is needed in this line:

  B* temp = new B;

because in case of throwed exception - compiler will automatically destructs temp...

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • Provide inline empty implementation of your virtual destructor in header file. There is no other way. Otherwise destruction of derived (S/B) is not possible. – PiotrNycz Nov 04 '12 at 02:43
  • thanks adding that line fixed my program. – user1202422 Nov 04 '12 at 02:48
  • I don't think the line with `B` actually can invoke any destructor, since if `new` throws it does so before completing the construction of `B` (actually before even starting it; it fails to get the raw memory), so the destructor `B::~B` will not be called. But this (a line calling for the _construction_ of a `B`) is as good a place as can be found for the compiler to warn you about the impossibility to destruct a `B`; either you will do that ultimately, or you've got a memory leak. – Marc van Leeuwen Jul 23 '14 at 12:37
  • @MarcvanLeeuwen An exception can be thrown from inside of `B::B()` after constructing its `A` part. So compiler needs to have access to implementation of `A::~A()`... I mean `B::~B() : A(), i(new int(13)) {}` In case of `bad_alloc` for `new int(13)` - `A::~A()` will be invoked... – PiotrNycz Jul 23 '14 at 14:57
  • @PiotrNycz: You are right, I overlooked that possibility. (And you meant `B::B()` where you wrote `B::~B()`; I'm sure you would never dream of calling `new` from a destructor.) – Marc van Leeuwen Jul 23 '14 at 16:13
1

According to your comment "Yeah i want A to basically be just a container class. Do not want any implementation of A". Your class B shall protected/private inherited from A instead of public inherite. virtual ~A() is allowed to be pure but you still need to provide implementation to ~A().

class A{
public:
  virtual ~A() = 0
  {
    cout << "~A"<<endl;
  }
};

class B : private /*protected*/ A{
  int *i;
public:
  B() : A(){
    i = new int;
  }
  ~B() {
    delete i;
  }
};

int main(){
    B* temp = new B;
    delete temp;
    return 0;
} 
billz
  • 44,644
  • 9
  • 83
  • 100