Reputation: 3
I have this code in C++:
#include <iostream>
class Object
{
public:
Object();
Object(int someValue = 0);
private:
int value;
};
Object::Object()
{
std::cout << "No argument constructor" << std::endl;
value = 0;
}
Object::Object(int someValue)
{
std::cout << "Argument constructor" << std::endl;
value = someValue
}
int main()
{
Object obj1; // should call Object() (according to me)
Object obj2(5); // should call Object(int) (according to me)
}
But the compiler (MinGW 4.8.1) on Windows 7 64 bit, complains about a call of overloaded 'Object()' being ambiguous:
defaultConstructorTest.cpp: In function 'int main()':
defaultConstructorTest.cpp:27:9: error: call of overloaded 'Object()' is ambiguous
Object obj1;
^
defaultConstructorTest.cpp:27:9: note: candidates are:
defaultConstructorTest.cpp:19:1: note: Object::Object(int)
Object::Object(int someValue)
^
defaultConstructorTest.cpp:13:1: note: Object::Object()
Object::Object()
^
So ideally, I would like to get this output:
No argument constructor
Argument constructor
Upvotes: 0
Views: 64
Reputation: 10733
This is because call to
Object obj1;
is ambiguous. As second constructor has one default argument which makes it a good enough contender for default construction of objects.
Upvotes: 3