c++classundefined-function

g++ compiler not generating error/warning for undefined methods


I have a class that has a declared method but not defined/used anywhere. I expected this piece of code to generate linking error but it did not. Looks like compiler is smart enough to remove dead code. Which default optimization is doing this? How can I explicitly disable it to generate the error?


#include <iostream>

using namespace std;

class Base{
public:
 int x;
 string name;
 void set(int val){ x = val;};
 int get(){ return x;}

 void Init();
};

int main() {
  Base base;
  base.set(10);
  cout << base.get() << endl;

  return 0;
}

EDIT1: Here Init() function is not defined and neither used anywhere. So, I expected compiler to complain about this not defined. But don't see any error/warning.

Thanks in advance.


Solution

  • Generally the linker will only produce errors for undefined symbols that are used. As you never call Init there is no error.