Why is a prototype required even without a class declaration?

If I just do this: Ex1:

#include <iostream> int main() { //try to call doSomething function doSomething(); } void doSomething() { std::cout << "Call me now!" << std::endl; } 

I get a compilation error! Since the compiler does not know what "doSomething" is.

But if I changed the position of doSomething to come in first place, the program successfully compiles. Ex2:

 #include <iostream> void doSomething() { std::cout << "Call me now!" << std::endl; } int main() { //try to call doSomething function doSomething(); } 

I can declare a prototype as follows: Ex3:

 #include <iostream> void doSomething(void); int main() { //try to call doSomething function doSomething(); } void doSomething() { std::cout << "Call me now!" << std::endl; } 

But why does the first example not work? Why do I even need to first declare a prototype or call functions and a main function?

Thank!

+4
c ++ function-prototypes
Nov 20 '11 at 2:45
source share
3 answers

You cannot call a function without a compiler, seeing either a definition or a declaration, at first simple. Before calling, a prototype or actual definition should appear.

+6
Nov 20 2018-11-11T00:
source share

Since the compiler did not see doSomething before using it.

Either you must prototype it, or define it first so that the compiler knows how to analyze its use.

+1
Nov 20 2018-11-11T00:
source share

This CC legacy is a one-pass language, which means that it should do everything just by reading the file once. To be able to call a function without a direct declaration / prototype, you need to read the file twice; First time find all function signatures and second time to compile.

C ++ retained this requirement for functions that were part of C, such as free functions and global variables. However, classes are new to C ++, and there was no need to keep the old way of doing something. Thus, as part of the definition of a single class, multi-pass compilation is used. This is why you can do this:

 class MyClass { void foo() {bar();} void bar() {} }; 

But you cannot do what you indicated in your question.

+1
Nov 20 '11 at
source share



All Articles