If suppose in a class I have two constructors
Room()
{
length = 0;
width = 0;
}
&
Room(int value = 8)
{
length = width = 8;
}
Now if from main I call using:
Room obj1;
obj.display();
which constructor will be called or will it throw error? I think that it will throw error as compiler will not be able to call the correct constructor because of two same type of constructors present.Is it correct ?
call of overloaded 'Room()' is ambiguous
so it won't be compile
and you can use codepad as an online compiler
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
In this case code will not compile... You can read more about default constructor from here
Assuming that this will be the complete program
#include <iostream>
struct Room
{
int length;
int width;
Room()
{
length = 0;
width = 0;
}
Room(int value = 8)
{
(void)value;
length = 8;
width = 8;
}
};
int main()
{
Room obj1; // ambiguous call
std::cout << obj1.length << "\n";
return (0);
}
This code will not compile because of an ambiguous call to the constructor of Room
for the declaration of obj1
.
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.