cuteCAT
cuteCAT

Reputation: 2311

C++ type overloading issue

I have 3 classes in a project, A, B and C. B is derived from A. And B can be constructed from C (it has a constructor B::B(C& c). If a method requires type B, I can use C instance instead.

Although C can be converted to B, I can not pass C directly as a parameter to functions requiring A.

void func(A a) {}
C c;
// calling func
func(c); // compile error
func(B(c)); // casting to B first; works.

Is it possible to have func(c) to compile? Due to some other factors, I cannot add constructor to construct A directly from C: A::A(C&) is not allowed.

Upvotes: 3

Views: 82

Answers (1)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

This compiles in VS2012:

class A { };
class B : public A { };
class C
{
public:
    operator B() { return B(); }   // User defined conversion.
                                   // This is pseudo code just to satisfy the syntax.
};

void func(A a) { }

int _tmain(int argc, _TCHAR* argv[])
{

    C c;
    func(c);
    func(B(c));
}

This is close to your code. Some adjustments might be needed.

Upvotes: 4

Related Questions