Sergey
Sergey

Reputation: 5

When calling derived class - error: taking address of temporary [-fpermissive]

I've been researching this error and could not find a resolution. I have a base class Convert with a virtual function compute(), and a derived class L_To_G (liters to gallons). In my main.cpp file, the statement:

p = &L_To_G(num);

gives me the following error:

../main.cpp: In function 'int main()':

../main.cpp:37:20: error: taking address of temporary [-fpermissive] p = &L_To_G(num);

Code in header file:

class Convert
{
  protected:
    double val1, val2; //data members
  public:
    Convert(double i) //constructor to initialize variable to convert
    {
        val1 = i;
        val2 = 0;
    }
    double getconv() //accessor for converted value
    {
        return val2;
    }
    double getinit() //accessor for the initial value
    {
        return val1;
    }
    virtual void compute() = 0; //function to implement in derived classes
    virtual ~Convert(){}
};

class L_To_G : public Convert  //derived class
{
  public:
     L_To_G(double i) : Convert(i) {}

     void compute() //implementation of virtual function
     {
        val2 = val1 / 3.7854;  //conversion assignment statement
     }
};

Code in main.cpp file:

int main()
{
    ...
  switch (c)
  {
     case 1:
     {
        p = &L_To_G(num);
        p->compute();
        cout << num << " liters is " << p->getconv()
        << " gallons " ;
        cout << endl;
        break;
      }
    ...

Upvotes: 0

Views: 3233

Answers (2)

khajvah
khajvah

Reputation: 5090

L_To_G(num) is a temporary object. You cannot assign pointer to temporary object. Use new keyword to allocate new memory for new object.

p = new L_To_G(num)

Upvotes: 2

The problem is unrelated to base or derived types, you are trying to make a pointer refer to a temporary, and that is not allowed:

T *p = &T(); // reproduces the same issue for any T

Upvotes: 2

Related Questions