2

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 .

2
  • 3
    C++11 allows for delegating constructors like in your second example, not calling them inside the body. It sounded like you were expecting an error from the first for that reason, so I wanted to make sure that was clear. Commented Nov 11, 2012 at 2:39
  • second Chris here, you should read about C++ Delegating Constructors. Reference: nullptr.me/2012/01/17/c11-delegating-constructors Commented Nov 11, 2012 at 5:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Please Explain a bit more.What should I replace.and than why it works for the replacement.I know I am breaking the rules but why the rules are not same for both the cases, as both should be erroneous.
There is exactly one spot in your code that you have the characters A(); right? That is not doing what you think it is doing. It is creating an unrelated temporary of type A then discarding it.
What does this statement do: int();? How about this function: void foo (){ A(); }? How about this function void bar() { A a = A(); }?
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.