PDA

View Full Version : QMap value type with virtual destructor



Vikram.Saralaya
24th November 2015, 14:34
Hello,

I solved a problem that troubled me for a while and now I am interested in getting more insight into what has been happening here..

I have a custom data type that I want to store as a value in QMap.

QMap<uint, CustomType>

My CustomType looks like:


class CustomType
{
public:
CustomType() { m_objectRef = nullptr; m_slotName = nullptr; }
CustomType(QObject* obj, const char* slotName) { m_objectRef = obj; m_slotName = slotName; }
virtual ~CustomType() {}

// Accessors
QObject* GetObjectName() { return m_objectRef; }
const char* GetSlotName() { return m_slotName; }

private:
QObject* m_objectRef;
const char* m_slotName;
};

I get a compilation error saying:

undefined reference to `_imp___ZTV10CustomType'

Solution:
Remove virtual keyword from the destructor.

My question:
Why can't I have a virtual destructor here?

Thank you!

Regards
Vikram

stampede
24th November 2015, 20:54
Do not store or pass polymorphic types by value, pass by reference, pointer or most preferably wrap your objects in smart pointers. Passing polymorphic objects by value can cause slicing.
Unrelated, but using constructor initializer lists instead of assigning in constructor body is a good habit.

prasad_N
25th November 2015, 07:05
Solution:
Remove virtual keyword from the destructor.

My question:
Why can't I have a virtual destructor here?

I tried your code actually it is getting complied with and without virtual.

Vikram.Saralaya
25th November 2015, 10:23
I tried your code actually it is getting complied with and without virtual.

I can confirm that I can easily reproduce that problem on my mingw-32bit compiler. Strange.. well I will stop worrying about it for now. Thanks for trying :)