+ 1
Question about constructors in C++
Why there is no output? Why doesnât an ambiguity error occur? https://code.sololearn.com/clKtHxtqnj8G/?ref=app
4 Answers
+ 1
@Donna
In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which constructor needs to be called.
+ 1
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "Class A";
}
A(int a = 0){
cout << "A";
}
};
int main() {
A a();
return 0;
}
So when we create an object âaâ of type âAâ ( A a(); ), compiler calls a constructor without parameters, doesnât he?
+ 1
I should have written âA a;â instead of âA a();â because compiler thinks that itâs a function declaration.