Calling Constructor with in constructor in same class

守給你的承諾、 提交于 2019-12-05 10:34:30
Vlad from Moscow

Inside this constructor:

A(int x, int y)
{
    a = x;
    b = y;
    A(); // calling the default constructor
}

call A(); creates a new temporary object that is immediately deleted after this statement. Because the default constructor A() does not initializes data members a and b then it outputs a garbage.

This temporary object has nothing common with the object created by constructor A( int, int ).

You could rewrite your class the following way:

class A
{
public:
    int a, b;

    A(): A(0, 0) {}

    A(int x, int y) : a(x), b(y)
    {
        cout << a << " " << b;
    }
};

You didn't call the default constructor, what you did is create a temporary A object, which happen to have its members uninitialized before you printed the output. Perhaps what you wanted to do is constructor delegation, which would look like

#include <iostream>

class A
{
    int a, b;
public:
    A(): A( 0, 0 ) {
        std::cout << a << ", " << b << std::endl;
    }
    A( int x, int y ): a( x ), b( y ) {}
}

int main()
{
    A object_a {}; //prints 0, 0
    return 0;
}

Here you output a and b which are not initialized:

A(){
cout<<a<<" "<<b;
}

And here you initialize a and b, but you create an anonlymous temporary object

A(int x , int y){
    a = x; b= y;
    A(); // !!!! CREATES AT TEMPORARY ANONYMOUS OBJECT WITH IT'S OWN a and B
}

To use a delegated constructor (i.e. using another constructor to finish the construction process of the SAME object) you have to use the delegeted constructor in the initialisation list :

A(int x , int y) : A() { a=x; b=y;  } 

Unfortunately, when you use delegation, the delegate must be the ONLY meminitializer in the list. This requires that the initialisation of a and b would happen after A().

Another alternative:

class A
{
public:
    int a, b;
    A() :  A(0, 0) { }  // use a delegated ctor 
    A(int x, int y) : a(x), b(y) { cout << a << " " << b; }
};

Still another alternative, using defaults (without reusing a constructor) :

class A
{
public:
    int a, b;
    A(int x=0, int y=0) : a(x), b(y) { cout << a << " " << b; }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!