Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

initialization failure

0 views
Skip to first unread message

thomas

unread,
Oct 1, 2008, 4:19:12 AM10/1/08
to
Hi,

------------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.

thomas

unread,
Oct 1, 2008, 4:31:04 AM10/1/08
to

ok, got it, cannot call constructor in a constructor.

soniso...@gmail.com

unread,
Oct 1, 2008, 4:39:58 AM10/1/08
to
On Oct 1, 4:19 pm, thomas <FreshTho...@gmail.com> wrote:
>         A(B *b){
>                 A(b->getInt());        //Line  2
>         }

> ---------------------------------------------------------


> 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

puzzlecracker

unread,
Oct 1, 2008, 9:07:10 AM10/1/08
to

> ok, got it, cannot call constructor in a constructor.

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(){

}

};

Obnoxious User

unread,
Oct 1, 2008, 11:03:06 AM10/1/08
to

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

puzzlecracker

unread,
Oct 1, 2008, 11:27:13 PM10/1/08
to

Opps, I was referring to calling the base class ctor. Sorry!

0 new messages