0

I am using Qt to develop an applicatio for which I am seeing a segmentation fault in my destructor of my virtual base class on exiting the application. I think it's to do with declaring the member variable static, but I'm not certain. Any pointers on what's going on would help. Below is my sample code. I have removed all the member functions for clarity.

In header file:

class Base : public QObject
{   
     public:
     Base() {}
     virtual ~Base() = 0; /// Fault occurs here in the debugger
};

class Child1: public Base
{
   public:
    Child1() {}
    ~Child1() {}
};

class Service 
{
   public:
     Service() {}
    ~Service() {}
private:
    static Child1 m_base;
};

In source file:

Child1 Service::m_base;

When I exit the application I get a segmentation fault in the Base class destructor. Is it because m_base static member variable does not exist at the time the destructor is called, but it's virtual!

BTW, I got rid of the problem by making m_base a pointer to Base class and instantiating it in definition, but I'd still like to know what's wrong with the code above.

Thanks!

GMahan
  • 93
  • 1
  • 2
  • 10
  • 5
    What compiler are you using? It should not have allowed you to instantiate a class with pure virtual functions. – inetknght Feb 05 '15 at 15:30
  • 1
    That shouldn't compile, even after adding the missing `;` and `public` specifiers. `Base` is abstract, so you can't declare a variable of that type. Please post code that compiles and demonstrates your error. – Mike Seymour Feb 05 '15 at 15:31
  • 3
    You must define the destructor (give it a body), even though it's pure virtual. Note you can't do it in-class. – n. m. could be an AI Feb 05 '15 at 15:31

1 Answers1

3

Your sample code is incorrect, because you cannot create an instance to Base, since it is abstract.

Please be more specific.

EDIT: I'm still not sure how this compiles, but You will have to add the Base destructor implementation:

Base::~Base()
{
}
Kiko
  • 319
  • 1
  • 4
  • 16
  • Sorry, my apologies. It's Child1 not Base. It was just a typo while writing this up. It's Child1 in the code. – GMahan Feb 05 '15 at 15:35
  • What do you mean "it's Child1" ? Correct your code accordingly please. – Jean-Baptiste Yunès Feb 05 '15 at 15:35
  • @GMahan Use the [edit](http://stackoverflow.com/posts/28347741/edit) link to correct your question. – n. m. could be an AI Feb 05 '15 at 15:38
  • I have made the corrections to the above code. – GMahan Feb 05 '15 at 15:46
  • Defining an implementation for the pure virtual base class destructor seemed to have solved the problem. Thanks for pointing this out. As for the compilation error, my original code (not posted here) seemed to compile OKAY, even without the implementation of the pure virtual destructor. However, when I tried to compile the code above it failed. I am not sure why the original code is compiling. – GMahan Feb 05 '15 at 16:17