5YrsLaterDBA
5YrsLaterDBA

Reputation: 34730

C++, #ifdef question

Not coding in C++ right now but a question came up when I have a question in C#. Hope experts here can easily give a anwser.

Class A{
  #ifdef AFlag
  public void methodA(){...}
  #endif
}

Class B{
...
  A a;
  a.methodA();
...
}

Class C {
...
  A a;
  a.methodA();
...
}

If the AFlag is NOT defined anywhere, what will happen? A compile error or no error but the methodA AND those statements calling that method will not be compiled? thanks

Upvotes: 1

Views: 289

Answers (7)

Steve Jessop
Steve Jessop

Reputation: 279215

Hard to say for certain, since code in the "..." could affect the answer, or mean that I've misunderstood the question. The statement a.methodA(); has to be in the body of a function.

You'll get compile errors at the lines a.methodA(); (or perhaps linker errors if the code is split across multiple translation units with inconsistent definitions of class A). Calling a function means it has to be there. The call is not "ignored" if the function doesn't exist.

Upvotes: 1

codaddict
codaddict

Reputation: 454920

Preprocessing happens before compilation. By the time your code goes to the compiler, the definition of method A in class A will be removed. Effectively its as if as you never wrote it. So this will result in compilation error.

Upvotes: 4

Bill
Bill

Reputation: 14675

You will have a complier error, as the function methodA is not declared anywhere. You could use this syntax instead:

Class A{ 

  public void methodA()
  {
#ifdef AFlag 
    ...
#endif 
  } 

} 

Which will allow methodA to be declared / defined, but it will be optimized away if you turn optimizations on.

Upvotes: 1

Colin Desmond
Colin Desmond

Reputation: 4854

You would see a compile error as the method methodA is not defined on class A.

Upvotes: 0

David R Tribble
David R Tribble

Reputation: 12204

If AFlag is not defined, class A won't have a member function methodA(), so the calls to it in class B and C will be errors.

Upvotes: 0

nos
nos

Reputation: 229058

Class A will not have an methodA so compiling class B or C will fail.

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

There will be a compile error.

Upvotes: 9

Related Questions