[Issue 22351] New: extern(C++) function contravariant in D, but not C++

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Oct 3 11:46:53 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=22351

          Issue ID: 22351
           Summary: extern(C++) function contravariant in D, but not C++
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: tim.dlang at t-online.de

////////////////// test.d ////////////////////////

extern(C++) class A
{
    int f()
    {
        return 1;
    }
}

extern(C++) class B: A
{
    override int f() const
    {
        return 2;
    }
}

extern(C++) B createB()
{
    return new B;
}

////////////////// test.cpp //////////////////////

#include <stdio.h>

class A
{
public:
    virtual int f();
};

class B: public A
{
public:
    virtual int f() const;
};

B *createB();

int main()
{
    const B *b = createB();
    printf("%d\n", b->f());
    return 0;
}

//////////////////////////////////////////////////

D allows to override the mutable function A.f with const B.f, because they are
contravariant. The vtbl for B only contains one entry for f. C++ does not
support that and expects a vtbl with two functions f. Calling b->f() results in
a segmentation fault, because the vtbl entry for B.f does not exist.

There are probably also other differences for covariant/contravariant functions
between D and C++.

--


More information about the Digitalmars-d-bugs mailing list