Why doesn't the following code give me duplicate symbolic links for Impl?
I ran into this problem in some code that I inherited, and for simplicity I am recreating a shorter version.
I have two classes: Foo and Bar, each of which defines a different version of the same structure (Impl) in each of its .cpp files. Thus, Foo.cpp and Bar.cpp have the same definition of Impl, but each of them has a different built-in design.
Both Foo and Bar have a member variable of type Impl, and each forward declares Impl in its .h file.
Foo.cpp will tell the instance of Bar inside its constructor. Interestingly, what is being created depends on the order in which the files are attached.
So this compilation command:
g++ -o a.out main.cpp Bar.cpp Foo.cpp
leads to this result:
==> main()
Bar.cpp Impl::Impl()
Bar.cpp Impl::Impl()
<== main()
And this command:
g++ -o a.out main.cpp Foo.cpp Bar.cpp
leads to this result:
==> main()
Foo.cpp Impl::Impl()
Foo.cpp Impl::Impl()
<== main()
gcc 4.1.2, Visual Studio 2008 Green Hills Multi 4.2.4, .
foo.h
#ifndef FOO_H
struct Impl;
class Bar;
class Foo
{
public:
Foo();
~Foo();
private:
Impl* p;
Bar* bar;
};
#endif
foo.cpp
#include <iostream>
#include "Foo.h"
#include "Bar.h"
struct Impl
{
Impl()
{
std::cout << "Foo.cpp Impl::Impl()" << std::endl;
}
};
Foo::Foo()
: p(new Impl),
bar(new Bar)
{
}
Foo::~Foo()
{
delete p;
delete bar;
}
bar.h
#ifndef BAR_H
#define BAR_H
struct Impl;
class Bar
{
public:
Bar();
~Bar();
private:
Impl* p;
};
#endif
Bar.cpp
#include <iostream>
#include "Bar.h"
struct Impl
{
Impl()
{
std::cout << "Bar.cpp Impl::Impl()" << std::endl;
}
};
Bar::Bar()
: p(new Impl)
{
}
Bar::~Bar()
{
delete p;
}
main.cpp
#include <iostream>
#include "Foo.h"
int main (int argc, char const *argv[])
{
std::cout << "==> main()" << std::endl;
Foo* f = new Foo();
std::cout << "<== main()" << std::endl;
return 0;
}