Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Function parameters create Classes

Tags:

c++

Say i have the following class :

class A
{
public:
    A() {
    }

    A(int a):_a(a){
    }

    int _a;
};

And the following function :

void someFunc (A a)
{
    cout << a._a;
}

So the following line in the program works fine :

someFunc (5); // Calls A(int a) Constructor.

But the following does not :

someFunc(); //Compile error

One can expect that if it can build A when getting an integer, why not build one using the default constructor as well, when called with no arguments?

like image 539
oopsi Avatar asked Dec 06 '25 08:12

oopsi


2 Answers

Because someFunc() requires an argument and you have not provided an overload which does not. An implicit conversion from int to A exists, but that doesn't mean you can just ignore the function's signature and call it with no arguments. If you would like to call it with no arguments them assign a default value to a.

void someFunc(A a = A()) { 
    /* stuff */
}
like image 169
Ed S. Avatar answered Dec 07 '25 20:12

Ed S.


Because you didn't call the function with an argument that turned out to be convertible, you called the function with no arguments. That's a different overload, one you haven't provided.

Consider these options:

  • Call the function like this: someFunc(A()).
  • Define a default value for the function parameter: void someFunc (A a = A()) { ... }.
  • Provide the no-argument overload: void someFunc() { someFunc(A()); }
like image 36
cdhowie Avatar answered Dec 07 '25 22:12

cdhowie



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!