Question

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.

Was it helpful?

Solution

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...

OTHER TIPS

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;
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top