M1Reeder
M1Reeder

Reputation: 722

C++ error: declaration of ‘~Destructor’ as member of ‘Class’

I compile using g++ -Wall -Werror *.cpp and get the error:

ConcreteCharArray.h:21:15: error: declaration of ‘~CharArray’ as member of ‘ConcreteCharArray’

Concrete implementation:

class ConcreteCharArray: public CharArray
{
private:
    char * charArray;
public:
   ~CharArray() {
      delete[] string;
   }
};

Virtual class:

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

Upvotes: 2

Views: 9968

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320719

Declaring a member named ~CharArray inside a class named ConcreteCharArray is simply illegal, which is what the compiler is telling you. The presence of ~ indicated that you are declaring a destructor, and the name of destructor must match the name of the class.

Destructors are special member functions. One of their special properties is that in order to override the virtual destructor of base class, you don't have to match the name of that destructor in the derived class (as you'd normally do with ordinary member functions). The compiler will match the destructors to each other automatically, even though their names are different. This is easy to do, since each class has one and only one destructor.

So, if you want to declare a destructor in class ConcreteCharArray you have to call that destructor ~ConcreteCharArray. There are no other options. Even though the name of derived destructor is different from the name of base destructor, the derived destructor will be treated as virtual and will override the base one.

Upvotes: 4

Related Questions