Re: Undefined reference to...
* Andrea Crotti, on 10.11.2010 19:08:
"Alf P. Steinbach /Usenet"<alf.p.steinbach+usenet@gmail.com> writes:
Well, that's what I'm wondering: what is the problem you're talking about?
Possibly I could find out by looking at your original posting.
But I don't think it's fair that I and other out to help you should do
a lot of work to figure out what you're talking about. Please try to
convey what you're talking about. "It doesn't work" out of context
says nothing, in particular, "It doesn't work" doesn't say what "It"
is.
Sorry you're right I was not clear, I was just continuing the
conversation with myself that's why...
Anyway I rephrase, first question is why this below doesn't find the
reference to the vtable?
class Base
{
public:
virtual void printOut();
};
class Extended : public Base
{
public:
void printOut() { cout<< "hello"; }
};
The only subclass actually implements the method I want, so should not
that be enough?
Or maybe it complains because the vtable is constructed at runtime
(giving the possibility of bad crashes if nothing is found)?
The compiler doesn't know that you're not creating any pure Base instances.
And it doesn't care.
A virtual member function, except a pure virtual member (that's a one with "= 0"
at the end) must have an implementation, so that the compiler can very
mechanically put the address of that implementation in the vtable, or use it in
whatever scheme it uses as an alternative to vtables.
The second question was if it was possible to do something like
class Extended;
class Base
{
public:
virtual void printOut() = 0;
static Base getLower() {
Extended e;
return e;
}
};
class Extended : public Base
{
public:
void printOut() { cout<< "hello"; }
};
Apparently not if I understand, then I'll find some other ways..
Problems with the above include
* 'getLower' attempts to return an object of abstract class.
* A local variable is declared with incomplete type 'Extended'.
* If those obstacles weren't in the way, 'getLower' would perform
a *slicing*, returning only the Base part of 'e', and then of type
'Base'.
It's not clear what you're attempting, but it may be that you want a Meyers'
singleton:
class Base
{
public:
virtual void printOut() = 0;
static Base& getLower();
};
class Extended: public Base
{
public:
void printOut() { cout << "hello"; }
};
Base& Base::getLower()
{
static Extended e;
// Whatever code you were intending to have here, then:
return e;
}
Note that with this scheme you always get the same object -- a singleton --
from 'getLower'.
Cheers & hth.,
- Alf
--
blog at <url: http://alfps.wordpress.com>