I have a base class(Base) whose constructor takes a reference as argument. In my derived class its constructor, I call the superclass-constructor and of course I need to pass a reference as argument. But I have to obtain that argument from a method of which the return type is by value…
I will give a short example:
class Base
{
public:
Base(MyType &obj) { /* do something with the obj */}
};
class Derived : public Base
{
public:
Derived(MyOtherType *otherType) :
Base(otherType->getMyTypeObj()) // <--- Here is the error because (see *)
{
// *
// getMyTypeObj() returns a value and
// the Base constructor wants a reference...
}
};
class MyOtherType
{
public:
MyType getMyTypeObj()
{
MyType obj;
obj.setData( /* blah, blah, blah... Some data */);
return obj; // Return by value to avoid the returned reference goes out of scope.
}
};
How can I solve this problem?
Change the Base class to:
class Base
{
public:
Base(const MyType &obj) { /* do something with the obj */}
};
Update: If you want to modify obj you cannot obviously have a
constreference. In that case you can either:1)Pass the parameter by value. That will have the overhead for the copy but avoid having to free it explicitly later.
2) Change
MyOtherType::getMyTypeObj()to}
In this case, remember to delete the object after you are done with it.