unixlover unixlover -4 years ago 136
C++ Question

Paranthesis vs curly braces

#include<iostream>
using namespace std;
class test
{
public:
int a,b;

test()
{
cout<<"default construictor";

}
test(int x,int y):a(x),b(y){

cout<<"parmetrized constructor";
}

};
int main()
{

test t;
cout<<t.a;
//t=(2,3);->gives error
t={2,3}; //calls paramterized constructor
cout<<t.a;
}


Output:- default construictor4196576parmetrized constructor2

why in case of the above example, parameterized constructor(even though default constructor is already called.) is called in case of {} and not in ()

Answer Source

I added some additional code to show what is actually happening.

#include<iostream>
using namespace std;

class test
{
    public:
    int a,b;

    test()
    {
        cout << "default constructor" << endl;
    }

    ~test()
    {
        cout << "destructor" << endl;
    }

    test(int x,int y):a(x),b(y)
    {
        cout << "parameterized constructor" << endl;
    }

    test& operator=(const test& rhs)
    {
        a = rhs.a;
        b = rhs.b;
        cout << "assignment operator" << endl;
        return *this;
    }

};

int main()
{

    test t;
    cout << t.a << endl;
     //t=(2,3);->gives error
     t={2,3}; //calls parameterized constructor
     cout << t.a << endl;
}

Output:

default constructor
4197760
parameterized constructor
assignment operator
destructor
2
destructor

So the statement t={2,3}; is actually constructing a new test object using the parameterized constructor, calling the assignment operator to set t to be equal to the new, temporary test object, and then destroying the temporary test object. It's equivalent to the statement t=test(2,3).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download