Re: Can this be done with a conversion operator in C++ ?
C++ is a strongly typed language,
Scala is statically typed as well. It even tries to get the utmost out of s=
tatic typing. See the explanation below.
You want to instantiate an object of type A, but get an object of
unrelated type B instead? How does that even make any sense?
I should have explained what is happening in the Scala code: The compiler s=
ees that class A has no method named bar(). Before it flags an error it loo=
ks for any conversion from class A to anything else and finds this here:
implicit def aToBWrapper(a: A) = {
println("before")
a.foo
println("after")
new B()
}
So it carries out the conversion and checks after that whether the compiler=
error is gone. As this is the case, things are fine and the Scala compiler=
continues. In case the implicit conversion (hence the keyword implicit in =
Scala) does not fix the problem, the Scala compiler stops and raises an err=
or. If it tried another conversion the compilation run could really continu=
e for a long time and even run wild.
@Paavo: Thanks for the C++ code snippet. Clever approach.
I was just asking here, because I saw something about a C++ conversation op=
erator and thought it might be able to do the same thing as Scala implicits=
.. From what I found meanwhile on the Internet it seems that conversion it C=
++ can only be to an built-in type.
This is not directly possible with C++ as in C++ the static type of a
variable (like a) is fixed at compile time, and this type must have a
method called bar, again at compile-time. At run-time the types and
actually called methods can be different, but only in a controlled way
(inherited classes and overridden virtual functions only).
Nevertheless, also in C++ one type of object can be converted implicitly=
into another type. Here is a way to get the same printout as in your
example:
#include <iostream>
class A {
public:
void foo() {
std::cout << "foo\n";
}
};
class B {
public:
B(A a) {
std::cout << "before\n";
a.foo();
std::cout << "after\n";
}
void bar() {
std::cout << "bar\n";
}
};
void bar(B b) {
b.bar();
}
int main() {
A a;
bar(a);
}