Rachit Agrawal
Rachit Agrawal

Reputation: 3343

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.

Upvotes: 2

Views: 150

Answers (2)

curiousguy
curiousguy

Reputation: 8298

Looks like compiler is smart enough to remove dead code.

The compiler is not even "smart" here. There is no code using a function so that function is not needed to produce an executable program.

The function is not even "ODR used" so technically the compiler would be wrong to require a definition.

Upvotes: 0

Alan Birtles
Alan Birtles

Reputation: 36488

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

Upvotes: 3

Related Questions