Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding C4673 compiler warning

The MSDN article on warning C4673 includes this example, which issues the warning with specific message:

Base: this base class is inaccessible
// C4673.cpp
// compile with: /EHsc /W4
class Base {
private:
   char * m_chr;
public:
   Base() {
      m_chr = 0;
   }

   ~Base() {
      if(m_chr)
         delete m_chr;
   }
};

class Derv : private Base {
public:
   Derv() {}
   ~Derv() {}
};

int main() {
   try {
      Derv D1;
      // delete previous line, uncomment the next line to resolve
      // Base D1;
      throw D1;   // C4673
   }

   catch(...) {}
}

Unfortunately, the MSDN article fails to give any explanation of the issue. I do not understand what's wrong with the above code. Why does it give a warning?

This is MSVC 2013 - v120 toolset.

like image 278
Violet Giraffe Avatar asked Jul 22 '15 11:07

Violet Giraffe


1 Answers

I can reproduce this on webcompiler and the full text of the warning is:

main.cpp(28): warning C4673: throwing 'Derv' the following types will not be considered at the catch site
main.cpp(28): warning C4670: 'Base': this base class is inaccessible

That is true. If we had:

try {
    throw Derv();
}
catch (Base& ) {
    std::cout << "I caught it!";
}

That handler wouldn't match the Derv exception, since Derv inherits privately from Base and so that base class is inaccessible. So in this example, the exception would be uncaught.

However, it's a weird warning to emit as in the MSDN example, the exception will be caught with:

catch(...) {}

So it seems that the warning doesn't actually check for anything - it's just a general-issuance warning that you may be doing something harmful, without actually checking if you are or not. That doesn't seem like a particularly useful warning to me. If we were catching by Base&, yes - tell me that that's not going to happen - but we're catching by ....

like image 80
Barry Avatar answered Oct 08 '22 02:10

Barry