Set reference of an abstract class by initialization list

I need to call an object of a class that initializes an interface by reference, the problem is that the object is needed during runtime but doesn't exist yet.

I've tried setting it as a constexpr so that the object is created during compile time but that doesn't seem to work. The class is called ltdc and an object needs to call the contructor eg. ltdcObject(Ltdc())

class Ltdc : public ILtdc
{
public:
constexpr Ltdc() noexcept {};
}


///////////////////////////////////////

class ILtdc
{
protected:

constexpr ILtdc() { }

public:

virtual ~ILtdc() {};
}
///////////////////////////////////////

class Ili9341 final
{
public:

Ili9341() noexcept;

ILtdc & ltdc; //Interface Ltdc Reference
}


///////////////////////////////////////

Ili9341:: Ili9341() noexcept :

ltdc(Ltdc()), //this is where it's called in the cpp file

{ }

error: #461 initial value of non-const must be an lvalue
You can't take a (non-const) reference of a temporary object. Won't work.
Also the constructor you're trying to call isn't in the code you pasted.
I'm not sure of a specific suggestion to give, other than don't pass in temporaries to something that expects a non-const reference.

Declare the object you're trying to pass as a variable (with a name) before you pass it to whatever constructor needs it. And make sure the lifetime of the reference doesn't outlive the lifetime of the object itself.
Last edited on
A reference is a synonym for another object. That means the other object must exist before you create the reference.

So in Ili9341, where do you expect the other object (the ILtdc) to come from? In your code you're passing in a temporary. In a case like that, there's no need to have a reference at all. Just make ltdc an object:
1
2
3
4
5
6
7
class Ili9341 final
{
public:
Ili9341() noexcept;

ILtdc ltdc; //Interface Ltdc
}

Topic archived. No new replies allowed.