From: Daniel Krügler on
On 7 Jul., 04:18, liam_herron <liam_her...(a)hotmail.com> wrote:
> Why does this compile when I define the body of the constructor in the
> header versus when I define the body of the constructor in the cpp file?
>
> // Works
>
> class A
> {
> public:
> A() {f();}
> virtual ~A() {}
> virtual void f() = 0;
> int a1_;
> };

What do you mean with "works" here?

Invoking a pure virtual function in the
constructor or destructor causes undefined
behavior. Many (most) implementations
will diagnose that, but that is not required.

Note that this category applies, even, if this
pure function does have a definition.

> // Generates Linker Error
> class A2
> {
> public:
> A2();
> virtual ~A2() {}
> virtual void f() = 0;
> int a2_;
> };

The linker error may have different reasons,
it usually is an implementation-specific outcome
of something the standard declares as causing
undefined behaviour. In this example the reason
could simply be because you invoked the pure
virtual function in the constructor or because you
did not compile the translation unit that contains
the constructor definition.

HTH & Greetings from Bremen,

Daniel Kr�gler


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Chris Uzdavinis on
On Jul 6, 9:18 pm, liam_herron <liam_her...(a)hotmail.com> wrote:
> Why does this compile when I define the body of the constructor in the
> header versus
> when I define the body of the constructor in the cpp file?

[snip code showing ctor invoking pure virtual function, inline and out-of-line]

Defining the constructor in the class declaration causes (requests) it to be
"inlined", such that code for the function doesn't normally get inserted into
your compiler's object code except at the point where it's called--but it's
not called from anywhere in your example and so no code is generated; the
linker never sees it. (Of course, if the compiler opts to not inline the
ctor afterall, then you would see the linker error in both of your examples.)

--
Chris

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]