If I have a foo.cpp file with the following code:
class Foo { }; class Foo { }; int main() { return 0; }
Then, of course, I get error: redefinition of 'Foo' . However, if I have foo.cpp with
class Foo { }; int main() { return 0; }
And bar.cpp with
class Foo { };
Despite the fact that class Foo is defined twice in the program, all this compiles fine.
If I put int something; into both files in the global namespace, then I would get a linker error (in particular, duplicate symbol ), but this will never happen to define classes.
I know that function declarations such as int doIt(); can be duplicated in both cpp files, but the definition, for example. int doIt() {} cannot be. Now in the first compiler error (with class Foo{}; twice in the same cpp file), he said redefinition of foo , so class Foo{}; is a definition. Then why, unlike functions, can this be determined twice in one program?
EDIT: According to this website , the named classes have an external link. So, why is there no collision between class Foo for both cpp files?
EDIT2:. According to the website above, not only classes with named external links, but also static members. But all this compiles fine:
foo.cpp :
class Foo { public: int foo(); static int x; }; int Foo::foo() { return 5; } int main() { return 0; }
bar.cpp :
class Foo { public: int foo(int); static bool x; }; int Foo::foo(int i) { return i * 2; }
Not only overriding Foo::foo with a different signature, but Foo::x has a different type. Both of them must have an external connection, but this code is A-ok.
c ++ class c ++ 11 linker
rcplusplus
source share