简体   繁体   中英

calling one constructor from another in same class

1) First Code

class A
{
public:
    int i;
    int b;
    A(int temp){
        i=temp;
        A();
        b=0;
    }

    A(){
        b=0;
    }

    void display(){
        printf("%d %d\n",i,b);//1 0
    }
};

int  main(){
    A Aobj(1);
    Aobj.display();
    return 0;
}

Output: 1 0

2) Second Code

class A
{
public:
    int i;
    int b;
    A(int temp) : i(temp), A(), b(0) {}//Error
    A() : b(0) {}
    void display(){
        printf("%d %d\n",b,i);
    }
};

int  main()
{
    A Aobj(1);
    Aobj.display();
    return 0;
}

I was expecting that both the codes will show same behavior and will produce an error as calling one constructor from the other in the same class is not permitted. It's not C++11.

So why does using the intializer list make a difference? I compiled this codes in g++ 4.3.4 .

A(); is not doing what you think it does.

Replace it with double(); or char(); or any other type. Note that it works.

All you are doing is creating an anonymous additional instance of the type then throwing it away. It has no impact on this and will not do what you think it does.

The initializer list works in C++11 the way you would expect.

This has nothing to do with C++11 at all.

As pointed out by Yakk in the first case, you construct an anonymous member non recursively through a different constructor (the default constructor).

In case 'B'; you try to initialize from the initialzier list a member that doesn't exist. You don't have an instance of A or an A* existing within A to initialize.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM