0

I know that when a compiler is compiling a function where an inline functions is called, the compiler must have access to the inline function definition and not just the inline function declaration. That is why we usually define the functions in the header file as well.

In the following when compiling main(), the compiler does not have access to the inline function definitions (Person::GetFirstName() and Person::GetLastName()), but it still compiles and runs.

If I remove or comment out all lines related to Person::GetString(), then the compiler behaves as expected by giving me link errors for inline functions (Person::GetFirstName() and Person::GetLastName()).

What is about Person::GetString() that it makes the definitions of inline functions Person::GetFirstName() and Person::GetLastName() accessible in another cpp file?

Person.h

#ifndef _PERSON_H_
#define _PERSON_H_

#include <string>

class Person
{
public:
    Person(const std::string& FIRST_NAME, const std::string& LAST_NAME, const size_t& AGE) : firstName(FIRST_NAME), lastName(LAST_NAME), age(AGE){}

    inline const std::string& GetFirstName() const;

    inline const std::string& GetLastName() const;

    const size_t& GetAge() const;

    const std::string GetString() const;
private:
    std::string firstName;
    std::string lastName;
    size_t age;
};
#endif

Person.cpp

#include "Person.h"
#include <sstream>
using namespace std;


inline const string& Person::GetFirstName() const
{
    return this->firstName;
}

inline const string& Person::GetLastName() const
{
    return this->lastName;
}

const size_t& Person::GetAge() const
{
    return this->age;
}

const string Person::GetString() const
{
    ostringstream strm;
    strm << this->GetFirstName() << "\t" << this->GetLastName() << "\t" << this->age;
    string result = strm.str();
    return result;

}

Main.cpp

#include <iostream>
#include "Person.h"
using namespace std;

int main()
{
    Person person("Jack", "Smith", 26);

    cout << "First Name: " << person.GetFirstName() << endl;
    cout << "Last Name: " << person.GetLastName() << endl;
    cout << "Age: " << person.GetAge() << endl;
    cout << endl;
    cout << person.GetString() << endl;
    return 0;
}

I am using Visual Studio Professional - 2103 Really appreciate any kind of help on this. Thank you.

Satya Sidhu
  • 103
  • 1
  • 9
  • If I remove or comment out all lines related to Person::GetString(), then the compiler behaves as expected by giving me link errors for inline functions (Person::GetFirstName() and Person::GetLastName()). What is about Person::GetString() that it makes the definitions of inline functions Person::GetFirstName() and Person::GetLastName() accessible in another cpp file? – Satya Sidhu Aug 18 '16 at 16:38
  • Smart linkers of today allow the inline definitions to go into a separate implementation file – sjsam Aug 18 '16 at 16:39

0 Answers0