Re: regarding Auto and decltype
On May 24, 10:45 am, ManicQin <manic...@gmail.com> wrote:
I have a question regarding the evaluation of the expression, in the
next scenario what should I expect:
class B {
public:
B() { }
virtual B* Clone() { return new B(); }
};
class D : public B {
public:
D() { }
virtual D* Clone() { return new D(); }
};
int main() {
B* tmp = new D();
auto test1 = tmp->Clone(); //returns D*!!!
decltype(tmp->Clone()) test2 = tmp->Clone();
return 0;
}
Please note That D::Clone overloads with a different return type.
That's called a covariant return type.
In my understanding if the "auto" is evaluating so it means that the
type of test1 should be D*, but VS10 understands different :) what am
I missing?
The type is determined at compile time, and the type of an expression
in C++ never changes. That is, the return type is NOT determined by
the
dynamic type of the return value, but of the static type at the point
where the call is made, at compile time.
Otherwise, imagine if it behaved what you seem to be wishing for:
// called with pointers to numerous types that all inherit from B...
void func(B * obj)
{
auto myClone = obj->Clone();
}
Ok, func is compiled *once*, and exists once in the application. For
auto to
declare an object of the dynamic type, that would require the body of
func()
to change depending on who called it.
That *could* work if func were a template, but it's not.
Maybe this makes it easier to see why the answer *has* to be the
static type (B*) and
not the dynamic type? If not, then consider one more thing.
Imagine your application has a plug-in interface, and 3rd parties can
provide
a shared library that your application will load. One function on
that shared library
is a factory function that produces objects that inherit from B.
extern B * generateObject();
When your application loads my library, it has NO idea what the real
type of object
I'll be returning, only its base class. To make the idea more
concrete, it's entirely
possibly your application is compiled, delivered, and installed,
before I ever even
started writing my library for it. So it's _impossible_ for your
application to know
anything about my code. Therefore, it should be clear that variables
in your code
do not (and cannot) refer to types in my code, without hiding behind
the polymorphic
interface.
Hope this helps.
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]