Why the following behavior occur? Is it a bug or normal behavior? (checked with Visual Studio 2013 and 2017) It seems using a virtual function as a getter or setter might not work as expected!
class A
{
public:
__declspec(property(put = SetWidth)) int width;
virtual void SetWidth(int value)
{
printf("A");
}
};
class B : public A
{
public:
virtual void SetWidth(int value) override
{
printf("B");
}
};
int main()
{
B b1;
B* b2 = new B();
b2->width = 4; // prints B
b1.width = 4; // prints A. why? it should print B!!!
(*(&b1)).width = 4; // prints B
(*b2).width = 4; // prints B
return 0;
}
Try using a dispatching function:
class A
{
public:
__declspec(property(put = SetWidth)) int width;
void SetWidth(int value)
{
SetWidthImpl(value);
}
private:
virtual void SetWidthImpl(int value)
{
printf("A");
}
};
class B : public A
{
private:
void SetWidthImpl(int value) override
{
printf("B");
}
};
That would mitigate the bug until it has been processed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With