2

I have created a class BWImage that inherits from Qimage. Objects of the class are thus of the type Qimage. After creating an object with:

BWImage image1;

How Do I now assign an actual image (already in the resource structure) to this object? I've tried this without luck:

image1 = QImage(":/lena.png"); 

As an overview of what I'm doing: Creating an image class with functions which I can call to perform fourier transforms etc.

László Papp
  • 51,870
  • 39
  • 111
  • 135
user3064874
  • 125
  • 1
  • 11
  • Create a constructor that does the work for you. See this [question](http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules) for more information. – jliv902 Apr 18 '14 at 14:39
  • Being a beginner, basic c++ is what I use. Also, being a beginner, it doesn't help me that much to know my idea is stupid and that I should use composition instead of aggregation. Suggested code, that helps. – user3064874 Apr 18 '14 at 14:44

2 Answers2

2

You cannot assign an object of base class to a derived one.

Your BWImage should provide a constructor accepting a filename, and call the QImage constructor.

BWImage(QString filename) 
  : QImage(filename) 
{
}
Bgie
  • 523
  • 3
  • 10
1

It is a bad idea here to inherit from QImage for this functionality because you will get your class having all the public interface methods that Image has.

This means your end users will have a bunch of methods available to call, whereas it seems your desire is just to allow them to call methods to execute algorithms, e.g. the aforementioned Fourier transformation. I would suggest to have a QImage member instead. This is also called "has-a" instead of "is-a" relation ship.

Either way, you will need to have the constructor or a method to set the QImage filename. I would write something like this:

imagehandler.h

#include <QImage>
#include <QDebug>

class ImageHandler
{
public:
    ImageHandler(const QString &fileName)
        : m_image(fileName)
    {
        ...
    }

    // Or just use an explicit method like this
    void loadImage(const QString &fileName)
    {
        if (!m_image.load(fileName)
            qDebug() << "Failed to load the image from file:" << fileName;
    }
    ...
private:
    QImage m_image;
}
László Papp
  • 51,870
  • 39
  • 111
  • 135