initialization failure

T

thomas

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;
}
 
T

thomas

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.

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

sonison.james

        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
 
P

puzzlecracker

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

}

};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top