1
votes

Person.h

#ifndef PERSON_H_
#define PERSON_H_

/* Person.h */

class Person {
  int age;
  std::string name;

  public:
    Person(int, std::string);
    std::string getName();
    int getAge();

};

#endif /* PERSON_H_ */

The person(int std::string) function declaration uses the std::string name, yet I have not included it in the header file. Thus, I would expect the compiler to complain about the missing symbol. Yet it compiles and runs fine! Why?

The rest of the code...

Person.cpp

#include <string>
#include "Person.h"

Person::Person(int age, std::string name)
{
  this->name = name;
  this->age = age;
}

std::string Person::getName()
{
  return this->name;
}

int Person::getAge()
{
  return this->age;
}

Main.cpp

#include <string>
#include "Person.h"

int main() {

  printFunc();

  Person chelsea_manning(5, std::string("Chelsea Manning"));

}

Also, I am new to C++, so please let me know if you see anything weird about my code / OOP.

1
Includes are like copy-pastes. Look at what copy-pasting those headers, in order, into your cpp would do.chris
Try removing #include <string> from both main.cpp and person.cpp and see what happens ;).mfontanini
try reversing the order of the includestay10r
Read up on "translation units" in C and C++.Yann Ramin
In general, header files should be written so that they compile on their own. To test this, write a trivial .cpp file that only has `#include "Person.h" and try to compile it.Pete Becker

1 Answers

5
votes

Compilation of a program begins at the top of the file that contains your main function (technically, the preprocessor is run before the program is compiled, but it still starts in the same place). In your case, the first thing it does is include <string> into that file. Then it includes Person.h. Since <string> was already included, all the content of the string file is ahead of the person file in your code and everything is declared in the proper order. If you were to include Person.h before <string>, or not include <string> in your main file, you would indeed receive a compilation error.

#include directions act like copy/paste: it literally reads the <string> file and slaps its contents into the source file that it's included from. Next, the same thing is done to Person.h. So the end result after running the preprocessor is

<-- contents of <string> -->
<-- contents of Person.h -->

int main()
...

So in your example, everything is declared in the correct order.