简体   繁体   中英

Why does the compiler complains when I declare and define a constructor with no argument and a constructor with an argument?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM