Why can the default copy constructor accept a static variable of type undefined?

Here is my code:

#include <iostream>

class Foo {
public:
    Foo() { std::cout << "Constructed" << std::endl; }
    // Comment 1.
    // Foo(const Foo& f) { std::cout << "Copy constructed." << std::endl; }
    void Miao() { std::cout << "Miao" << std::endl; }
};

class Bar {
public:
    static Foo f;
};

// Comment 2.
// Foo Bar::f;
Foo x(Bar::f);

int main() {
    x.Miao();
    return 0;
}

Result:

Miao

And if I try to overload the copy constructor Foo(uncomment Comment 1), a compilation error occurs:

/tmp/ccuF5B5q.o: In function `__static_initialization_and_destruction_0(int, int)':
default.cpp:(.text+0x51): undefined reference to `Bar::f'
collect2: error: ld returned 1 exit status

My OS is ubuntu-14.04.5 and the g ++ version is 4.8.4.

I am confused why this code works well?

Thanks in advance: p

+4
source share
1 answer

You did not specify a definition for Bar::f. Thus, any odr use of this object will result in a linker error. Your reception of a link to it is considered so.

odr , , , , ODR . .

+3

Source: https://habr.com/ru/post/1666095/


All Articles