문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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;
} 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top