0

I would like to have a static const object with some attributes set to some variable. To do this I've thought to derive the class and set the attributes in the derived class. Now I have to share the const object with other class, but to do this I should first cast it to the base class but I get an error.

class QAudiolib
{
private:
    class DefaultAudioFormat : QAudioFormat
    {
        DefaultAudioFormat()
        {
            setByteOrder(QAudioFormat::LittleEndian);
            setChannelCount(2);
            setCodec("audio/pcm");
            setSampleRate(44100);
            setSampleSize(16);
            setSampleType(QAudioFormat::SignedInt);
        }
    };

    static const DefaultAudioFormat DEFAULT_FORMAT;

public:
    QAudiolib();

    static QAudioFormat getDefaultFormat()
    {
        return reinterpret_cast<QAudioFormat>(DEFAULT_FORMAT);
    }   

};

The compiler gets this error on the cast line

error: 'QAudioFormat' is an inaccessible base of 'QAudiolib::DefaultAudioFormat'
         return (QAudioFormat)(DEFAULT_FORMAT);
                                             ^

What have I to do?

Andrea993
  • 663
  • 1
  • 10
  • 23

2 Answers2

2

Write class DefaultAudioFormat : public QAudioFormat instead.

This makes the inheritance public, and therefore accessible.

I don't like the use of the reinerpret_cast though: why not simply return DEFAULT_FORMAT and leave the rest to the compiler?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

The compiler error is because the default inheritance is private (for classes and public for structs), so you get rid of it by using

class DefaultAudioFormat : public QAudioFormat

Besides that, you should also return by const reference, because now you do a copy (you create a new QAudioFormat object instead of passing the original DefaultAudioFormat object), which results in slicing (although if every attribute is actually part of QAudioFormat then it is not such a big issue, but still).

If everything is set properly, you shouldn't need to do any typecast here. Like this:

static const QAudioFormat & getDefaultFormat()
{
    return DEFAULT_FORMAT;
}
EmDroid
  • 5,918
  • 18
  • 18
  • Yes, by reference is better – Andrea993 Feb 08 '16 at 12:14
  • @axalis: Please feel free to take the inheritance part from my answer: your point about changing the return type is, IMHO, more important. This ought to emerge as the better answer. – Bathsheba Feb 08 '16 at 12:16