Ferenc Deak
Ferenc Deak

Reputation: 35408

Creating a derived class from a base

I get the following error message:

conversion from ‘BaseClass’ to non-scalar type ‘DerivedClass’ requested

while compiling something like:

AnotherClass response;
DerivedClass message = response.serialize(QString("someStuff"));

where I have

BaseClass AnotherClass::serialize( const QString& valueName ) const

and

class DerivedClass : public BaseClass
{
    ...
    DerivedClass &operator=(const BaseClass &other);
}

Can someone explain what is wrong here, and more importantly why?

Upvotes: 0

Views: 64

Answers (2)

Besides using copy-initialization, not assignment as you think you are, you are also violating the rule of three/four.

The rule is that if you have any of the below, you must have all of them (either implemented or deleted using Q_DECL_EQ_DELETE):

  1. Destructor

  2. Copy Constructor

  3. Move Constructor (for C++11)

  4. Assignment Operator

For example, suppose you don't want to implement assignment. You should have:

class MyClass {
  // private, deleted - compatible with both C++11 and C++98/03.
  MyClass & operator=(const MyClass &) Q_DECL_EQ_DELETE;
public:
  MyClass(const MyClass &);
  MyClass(MyClass &&);
  virtual ~MyClass();
  ...
};

Upvotes: 0

jrok
jrok

Reputation: 55395

DerivedClass message = response.serialize(QString("someStuff"));

This is copy-initialization, not assignment, and operator= doesn't even come in play.

You either need a constructor that takes BaseClass or write it like this:

AnotherClass response;
DerivedClass message;
message = response.serialize(QString("someStuff")); // assignment

Upvotes: 3

Related Questions