I have a question about this:
class A
{
int a;
int* pa;
public:
A(int i):a(i) , pa(new int(a))
{
cout<<"A ctor"<<a<<endl;
}
~A()
{
delete pa;
cout<<"dtor\n";
}
int * &get()
{
return pa;
}
};
class B : public A
{
int b;
public:
B (A obj): A(obj) , b(0)
{
cout<<"B ctor\n";
}
~B()
{
cout<<"B dtor\n";
}
};
int main()
{
int i = 23 ;
A* p = new B(i);
}
Can tell me why the last line in main
compiles? I pass an int
into B
's constructor which expects an A
object instead. I believe that the int
is translated to an A
in B
's constructor, but why?
Thanks in advance.
Avri.
Since you have not declared A
constructor as explicit
compiler is creating an anomymous instance of A
using i
and using it to initialize B
instance. If you don't want the compiler to do these implicit conversions declare your costructor as explicit
. Then you will get a compiler error.