Sign in to follow this  

Inheritance and function overloading

This topic is 3040 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I've stumbled over a problem. The following code prints "1" and not as I expected "2". Why is that?
int convert(a @data) // const a &in data produces the same result
{ 
  return data.i; 
}

int convert(b @data) // const b &in data produces the same result
{ 
  return data.j; 
}

class a 
{ 
  int i; 
  int internal_convert() 
  {
    return convert(this);
  } 
}

class b:a 
{ 
  int j; 
}

b tB;
tB.i = 1;
tB.j = 2;
print(tB.internal_convert());


Is this the normal behaviour? Thanks, Tim

Share this post


Link to post
Share on other sites
This is expected behaviour, because which convert function to call is chosen at the moment the internal_convert function is compiled. class b inherits the internal_convert function from class a, but it doesn't recompile it to use the other convert function.

This is also what would happen in C++.

You can use polymorphing instead of function overloads to get what you want, i.e.:


int convert(a @data)
{
b @data_b = cast<b>(data);
if( data_b !is null )
return data_b.j;

return data.i;
}



Share this post


Link to post
Share on other sites

This topic is 3040 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this