+ 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

13th May 2018, 10:47 AM
Daniil Ivanov
Daniil Ivanov - avatar
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.
13th May 2018, 11:18 AM
Daniil Ivanov
Daniil Ivanov - avatar
+ 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?
13th May 2018, 11:25 AM
Daniil Ivanov
Daniil Ivanov - avatar
+ 1
I should have written “A a;” instead of “A a();” because compiler thinks that it’s a function declaration.
14th May 2018, 6:42 AM
Daniil Ivanov
Daniil Ivanov - avatar