0

I have a code as below and I don't understand why exactly compiler can't infer the constructor to be used when instance of D class is created. I have deleted both copy and move constructor so the only alternative would be to use A(Base&)

Is there are a way to tell compiler to use A(Base&) constructor, besides casting *this to Base&.

class Base {};

class A
{
    private:
    Base& m_b;
    public:

    A(Base& b) :m_b(b) {}
    A(const A&) = delete;
    A(A&&) = delete;
};

class D : public Base, public A
{
    public:
    D():A(*this){}

};

int main()
{  
    D();
}

The error I'm getting is as follows:

main.cpp: In constructor 'D::D()':
main.cpp:17:16: error: call of overloaded 'A(D&)' is ambiguous
     D():A(*this){}
                ^
main.cpp:10:5: note: candidate: A::A(const A&) <deleted>
     A(const A&) = delete;
     ^
main.cpp:9:5: note: candidate: A::A(Base&)
     A(Base& b) :m_b(b) {}
senx
  • 630
  • 9
  • 18

2 Answers2

1

Add a cast:

D():A(static_cast<Base&>(*this)){}

This will force the expression to have the type which matches your desired overload.

Simply deleting a function or c'tor doesn't remove it from the overloads set, which is why you see an ambiguity. It would only make the compiler consider the program as ill-formed if the function is ever chosen from all available overloads.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

You can cast the pointer before dereferencing it:

D() :A(*(Base*)this) {}

or

D() :A(*static_cast<Base*>(this)) {}
roalz
  • 2,699
  • 3
  • 25
  • 42
8znr
  • 336
  • 3
  • 13