Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem understanding explicit constructor in C++
    text
    copied!<p>After reading this thread <a href="https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean">What does the explicit keyword mean in C++?</a></p> <p>I made up this program</p> <pre><code>class MyClass { public: explicit MyClass(int a) { cout&lt;&lt;"Int was called"&lt;&lt;endl; val = a; } MyClass(char *a) { cout&lt;&lt;"Char was called"&lt;&lt;endl; val = atoi(a); } MyClass(const MyClass&amp; copy) { cout&lt;&lt;"Copy Const was called"&lt;&lt;endl; this-&gt;val = copy.val; } inline const int getval() const { return val; } private: int val ; }; </code></pre> <p>main code</p> <pre><code>int main() { int x=4; char y='4'; char *z = &amp;y; MyClass a(x); MyClass b(z); MyClass c(a); MyClass d('4'); cout&lt;&lt;a.getval()&lt;&lt;endl; cout&lt;&lt;b.getval()&lt;&lt;endl; cout&lt;&lt;c.getval()&lt;&lt;endl; cout&lt;&lt;d.getval()&lt;&lt;endl; return 0; } </code></pre> <p>The output was:</p> <pre><code>Int was called Char was called Copy Const was called Int was called 4 4 4 52 </code></pre> <p>Now, as per thread above, it should throw error after the constructor call on object d but it didn't. </p> <p>g++ version info</p> <pre><code>Using built-in specs. Target: i486-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.3-4ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-plugin --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu Thread model: posix gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) </code></pre> <p>I am not sure if i have done something wrong in the above code. Please help</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload