www.digitalmars.com         C & C++   DMDScript  

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


          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 puremagic.com
          Reporter: tim.dlang 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
    virtual int f();

class B: public A
    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++.

Oct 03 2021