1

Trying to add functionality to QString but get build errors ?? And if I am missing things??

#ifndef CSTRING_H
#define CSTRING_H

#include <QString>
#include <QStringList>
#include <QObject>


class CString : public QString, public QObject
{
    Q_OBJECT
public:
    explicit CString(QObject *parent = 0);
    QStringList Find(QString qstrSearch);//all occurances

signals:

public slots:

};

#endif // CSTRING_H

#include "cstring.h"

CString::CString(QObject *parent) :
    QString(parent)     //ERROR IS POINTING TO HERE
{
}


QStringList Find(QString qstrSearch)//all occurances
{//indexOf, contains
    QStringList qstrList;



    return qstrList;
}

Build error

SpongeBobFan
  • 964
  • 5
  • 13
jdl
  • 6,151
  • 19
  • 83
  • 132
  • What is your question? – maditya Aug 05 '13 at 23:52
  • Why the build errors? And if I am missing things – jdl Aug 05 '13 at 23:53
  • 9
    Subclassing QString is a bad idea -- QString does not have a virtual destructor, and QStrings get passed by value a lot which means you are likely to get bit by object slicing. A better approach would be to create free functions instead (i.e. not member functions, just functions that take and/or return QString objects) – Jeremy Friesner Aug 05 '13 at 23:57
  • 5
    The immediate cause of the error: `QString` is not derived from `QObject` and doesn't have a constructor that takes `QObject*`, so don't try to initialize it with one. I concur with Jeremy Friesner - QString is not designed to be derived from. You want to reconsider your design. – Igor Tandetnik Aug 06 '13 at 00:15

3 Answers3

2

QString(parent) Qstring does not have a constructor taking a QObject-parent as parameter. Therefor the compiler tries to cast your QObject to closest Matching constructor, which probably would be QString ( QChar ch )

Sebastian Lange
  • 3,879
  • 1
  • 19
  • 38
2

You should use composition instead of inheritance here, because QString is not designed for subclassing. You can get a lot of troubles if you will subclass it.
Do something like this:

class CString : public QObject //if you're really need this class to be QObject, that's not always a good idea
{
    Q_OBJECT
public:
    explicit CString(QObject *parent = 0) : 
        QObject(parent), 
        mString() //QString have no constructors with parameter QObject*...
    {
    }

private:
    QString mString;
}

Of course, implementation should be in cpp file, it's just a short example

SpongeBobFan
  • 964
  • 5
  • 13
2

Don't derive classes form QString since it wasn't designed with polymorphy in mind (note that it has no virtual methods, in particular no virtual destructors) If you want to provide new utility functions, just use free functions - you may want to put them in a namespace:

namespace CString {
    QStringList find(const QString &search);
}
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207