Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor c++

I am trying to understand how default constructor (provided by the compiler if you do not write one) versus your own default constructor works.

So for example I wrote this simple class:

class A
{
    private:
        int x;
    public:
        A() { std::cout << "Default constructor called for A\n"; }
        A(int x)
        {
            std::cout << "Argument constructor called for A\n";
            this->x = x;
        }
};

int main (int argc, char const *argv[])
{
    A m;
    A p(0);
    A n();

    return 0;
}

The output is :

Default constructor called for A

Argument constructor called for A

So for the last one there is another constructor called and my question is which one and which type does n have in this case?

like image 498
CubSqared Avatar asked Dec 03 '25 10:12

CubSqared


2 Answers

 A n();

declares a function, named n, that takes no arguments and returns an A.

Since it is a declaration, no code is invoked/executed (especially no constructor).

After that declaration, you might write something like

A myA = n();

This would compile. But it would not link! Because there is no definition of the function n.

like image 193
René Nyffenegger Avatar answered Dec 05 '25 22:12

René Nyffenegger


A n();

could be parsed as an object definition with an empty initializer or a function declaration.

The language standard specifies that the ambiguity is always resolved in favour of the function declaration (§8.5.8).

So n is a function without arguments returning an A.

like image 23
manlio Avatar answered Dec 05 '25 22:12

manlio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!