5

I'm a bit hazy on the rules of declarations vs. definitions.

I have the following declaration in funcs.h:

void sumTotalEnrgyAndClush(Protein &A,Protein &B,double ans[2],double enrgyA[18][18],double     enrgyB[18][18]);

Notice that ans[2] is before enrgyA and B.

In the funcs.cpp file the definition starts like this:

void sumTotalEnrgyAndClush(Protein &A,Protein &B,double enrgyA[18][18],double enrgyB[18][18],double ans[2])

It compiles (via makefile) and works fine.

I also noticed that if I remove the declaration the compiler seems to manage just fine.

Why doesn't the change in the order of the arguments matter? Is it that the last 3 items are all pointers so the difference in order doesn't matter?

4
  • possible duplicate of What is the difference between a definition and a declaration? Commented Aug 26, 2010 at 14:49
  • 2
    Not a duplicate; actually an interesting question. Commented Aug 26, 2010 at 14:51
  • The change in order does matter. EDIT: James McNellis said it better in his answer. Commented Aug 26, 2010 at 14:52
  • A really good and interesting question. Commented Aug 26, 2010 at 14:53

1 Answer 1

12

Why doesn't the change in the order of the arguments matter?

The order does matter. In C++, functions can be overloaded, so two or more functions can have the same name if they have different parameters (or, if they are member functions, if they differ in const-qualification).

You have actually declared two sumTotalEnrgyAndClush functions. The declaration in the header file declares one function that is never defined, and the declaration in the source file declares and defines a second function.

If you tried to use the function declared in the header file (by calling it or taking its address, for example), you would get an error because that function is not defined.

Sign up to request clarification or add additional context in comments.

2 Comments

What originally confused me was that my program was working in spite of what you mentioned in your last sentence. I've since noticed that there was an additional definition in my main.cpp file that matched the declaration in the funcs.h file. But your answer was a great addition to my general knowledge. Thanks.
@Dave: If you stick to a set of rules where the definitions go for things declared in headers (like everything in x.h is defined in x.cpp), you won't end up having multiple (different) definitions for the same thing. Once you're in a real big project (thousands of source files), you will need this, or you're never be able to find your way around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.