------------code--------------------------------------
#include<iostream>
using namespace std;
class B{
int y;
public:
B(int b=3):y(b){}
int getInt(){
return y;
}
};
class A{
int x;
public:
A(const int &x_){ //Line 1
x=x_;
}
A(B *b){
A(b->getInt()); //Line 2
}
int getInt(){
return x;
}
};
int main(){
B *b = new B;
A *a = new A(b);
cout<<a->getInt()<<endl;
}
---------------------------------------------------------
I expected that in line 2, "b->getInt()" is 3, and by calling
construction function of Line 1, the printed result should be 2;
But it's 0, can anyone tell me the reason? Thanks in advance.
ok, got it, cannot call constructor in a constructor.
> ---------------------------------------------------------
> I expected that in line 2, "b->getInt()" is 3, and by calling
> construction function of Line 1, the printed result should be 2;
>
> But it's 0, can anyone tell me the reason? Thanks in advance.
This is because in Line 2, x member of the current object is not being
initialized, instead a new A object is created and it's x is
initialized. You need to simply initialize x of the current object.
A(B *b)
{
// probably have a check to see that b is not NULL before
accessing b ptr
x = b->getInt();
}
Thanks and regards
Sonison James
sure you can, in your case, as someone already mention, you're
creating a new object.
Here is how you can call another ctor
class A{
A(){}
A():this(){
}
};
No you can't.
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.3
--
OU
Remember 18th of June 2008, Democracy died that afternoon.
http://frapedia.se/wiki/Information_in_English
Opps, I was referring to calling the base class ctor. Sorry!