Jump to content

Passing arguments by reference / inheritance bug


photo

Recommended Posts

I'm seeing inconsistent and unexpected behaviour when trying to set variables passed by reference (possibly related to inheritance). See example below:

 

 

 

class MyBase
{
public:
   void TestSetByReference(int& result)
   {
       result = 17;
   }
};


class MyDerived : MyBase
{
public:
   void TestSetByReference(int& result)
   {
       result = 34;
   }
};


MyBase base = new MyDerived();
MyDerived derived = new MyDerived();

int i = -1;
derived.TestSetByReference(i);
log.message("derived.TestSetByReference = %d \n",i);

i = -1;
base.TestSetByReference(i);
log.message("base.TestSetByReference = %d \n",i);

i = -1;
MyBase(base).TestSetByReference(i);
log.message("MyBase(base).TestSetByReference = %d \n",i);

i = -1;
MyBase::TestSetByReference(i);
log.message("MyBase::TestSetByReference = %d \n",i);

i = -1;
MyDerived(base).TestSetByReference(i);
log.message("MyDerived(base).TestSetByReference = %d \n",i);

i = -1;
MyBase(base).TestSetByReference(i);
log.message("MyBase(base).TestSetByReference = %d \n",i);

 

 

// Output:

derived.TestSetByReference = 34

base.TestSetByReference = 0 <--- ??

MyBase(base).TestSetByReference = 0 <--- ?? The same call gives a different result below

MyBase::TestSetByReference = 17

MyDerived(base).TestSetByReference = 34

MyBase(base).TestSetByReference = 17 <--- ?? Different result, but still wrong

 

Performing the same example except returning by value gives expected results (i.e. result is always 34, except when base class method is explicity called via MyBase:: )

 

Is this a known bug or limitation?

Link to comment
×
×
  • Create New...