-3

Possible Duplicate:
What does the explicit keyword in C++ mean?

I do not understand the following. If I have:

class Stack{
    explicit Stack(int size);
}

without the keyword explicit I would be allowed to do:

Stack s;
s = 40;

Why would I be allowed to do the above if explicit wasn't provided?? Is it because this is stack-allocation (no constructor) and C++ allows anything to be assigned to the variable unless explicit is used?

Community
  • 1
  • 1
user997112
  • 29,025
  • 43
  • 182
  • 361

2 Answers2

6

This line

s = 40;

is equivalent to

s.operator = (40);

Which tries to match the default operator = (const Stack &). If the Stack constructor is not explicit, then the following conversion is tried and succeeds:

s.operator = (Stack(40));

If the constructor is explicit then this conversion is not tried and the overload resolution fails.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • What is wrong with s.operator = (Stack(40)); ? Isn't that legal and we just want to prevent the number 40 being assigned? – user997112 Jan 19 '13 at 19:49
  • @user997112: `s.operator = (Stack(40))` is legal, but it is an *explicit* call to the constructor. The point is that this version isn't tryied if the constructor is said to be `explicit`. – Yakov Galka Jan 19 '13 at 21:12
1

hey its pretty simple . the explicit key word only stops complier from automatic conversion of any data type to the user defined one.. it is usually used with constructor having single argument . so in this case u are jus stopping the complier from explicit conversion

#include iostream
 using namespace std;
class A
{
   private:
     int x;
   public:
     A(int a):x(a)
      {}
}
 int main()
{
A b=10;   // this syntax can work and it will automatically add this 10 inside the 
          // constructor
return 0;
}
but here

class A
{
   private:
     int x;
   public:
    explicit A(int a):x(a)
      {}
}
 int main()
{
A b=10;   // this syntax will not work here and a syntax error
return 0;
}