+ 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
3 odpowiedzi
+ 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.