Andrea993 February 2016

Cast a static const object to base class

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?

Answers


Bathsheba February 2016

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?


axalis February 2016

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;
}

Post Status

Asked in February 2016
Viewed 2,688 times
Voted 7
Answered 2 times

Search




Leave an answer