pitastic
pitastic

Reputation: 332

Does the order of declaring functions and methods in C++ matter

In C when you use a function before declaring it the compiler assumes that is takes no parameters and returns and int.
If your function returns another type or takes parameters then the compiler produces an error.
Does the same happen in C++ if I make an object of a class that is declared later on in the code?

Upvotes: 3

Views: 4216

Answers (3)

anderas
anderas

Reputation: 5844

In C++ there is no implicit declaration, neither of classes nor of functions. So your question does not apply directly.

If you call a function or create an object of a given type, that function/type has to be declared before the first use. Functions do not necessarily have to be defined. and classes only have to be defined when actually instantiating them, or using them as (member) variables. When only a pointer to a class is needed a declaration is not needed, as a forward-declaration is sufficient until the memory of the actual object is allocated or functions are called on the object.

Upvotes: 4

cwfighter
cwfighter

Reputation: 502

In early c++ version, if you define the function test(int a), it will return a int type value by default. But after c++ becoming standard, the function will get an error. You can find the introduction in the book c++ Primer, the function chapter.

Upvotes: 0

cvangysel
cvangysel

Reputation: 301

The order does matter. If you reference a function which has not been declared (just the signature and return type, no implementation) then the compiler will throw an error. The definition of your function can wait until link time. AFAIK, there is not implicit declaration in C++.

Usually you put the declarations of your functions in header files. Traditionally, the symbols exported by a translation unit (usually a stand-alone source file e.g., hello.cpp) will be made available through a similarly-named header file (e.g., hello.h). The implementation then follows in the source file. Every translation unit can then include header files from other translation units (e.g. other.h).

Every translation unit gets compiled individually (i.e. a source file such as hello.cpp; all #include preprocessing statements are replaced by the actual contents of the files to be included). At link time, the implementations of the functions in different translation units get linked together. If this linking step fails, then you can still encounter errors.

Upvotes: 4

Related Questions