Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__declspec(property) and virtual functions

Tags:

c++

visual-c++

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;
}
like image 496
Ruchira Hasaranga Avatar asked Jun 05 '26 14:06

Ruchira Hasaranga


1 Answers

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.

like image 145
Guillaume Racicot Avatar answered Jun 07 '26 23:06

Guillaume Racicot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!