Frage

I ham having three classes in my program,

class A {
public:
  virtual ~A() {
    decompose();
  }
  virtual void decompose();
};

class B:public A {
private:
  int *b_data;
public:
  void decompose() {
    if (b_data != NULL) delete [] b_data;
  }
};

class C:public A {
private:
  int *c_data;

public:
  void decompose() {
    if (b_data != NULL) delete [] c_data;
  }
};

But when I compile this code with g++, I get the error:

In function `~A':
undefined reference to `vtable for A'
undefined reference to `A::decompose()'

In function `A':
undefined reference to `vtable for A'
undefined reference to `typeinfo for A'
undefined reference to `typeinfo for A'

If it helps, class A is defined in a .h file and it's destructor is defined inline, and two other classes have two files .h and .cpp.

In my program I call these classes according to the following:

int main() {
  A *a;
  a = new B();  //constructor is defined
  delete a;
  return 0;
}

Is there a problem with this code?

War es hilfreich?

Lösung 2

The error is caused due to a call to A::decompose in B and C destructors. The A::decompose is called even if destructors are virtual and method is virtual itself. When A destructor is run for derived objects B or C, the derived part of the object was already destroyed.

class A {
public:
  virtual void decompose() { std::cout << "A";}
  virtual ~A() {
    decompose();
  }
};

class B:public A {
private:
  int *b_data;
public:
  void decompose() {
      std::cout << "B";
    if (b_data != NULL) delete [] b_data;
  }
};

class C:public A {
private:
  int *c_data;
public:
  void decompose() {
      std::cout << "C";
    if (c_data != NULL) delete [] c_data;
  }
  ~C() {}
};

int main(int argc, char** argv) {
    B b;
    C c;
    return 0;
}

Output:

AA


Solution:

class A {
public:
  virtual void decompose() = 0;
  virtual ~A() {
      std::cout << "~A";
  }
};
class B:public A {
private:
  int *b_data;
public:
  void decompose() {
      std::cout << "B_decompose"; if (b_data != NULL) delete [] b_data;
  }
  ~B() { std::cout << "~B";}
};

class C:public A {
private:
  int *c_data;
public:
  void decompose() {
      std::cout << "C_decompose"; if (c_data != NULL) delete [] c_data;
  }
  ~C() { std::cout << "~C";}
};
   int main(int argc, char** argv) {
       B b;
       C c;
        A* p = &b;
        p->decompose();
        p = &c;
        p->decompose();
        return 0;
    }

compiled example

compiled example (solution)

Andere Tipps

Be careful calling virtual functions in constructors and destructors. They are not overriden as normal. A(..) and ~A() ALWAYS call A::decompose. I think the compiler is complaining it cannot find this function.

Create an implementation of your A::decompose function in your base class

virtual void decompose(){};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top