c++ - Why does this virtual method return true? -
while taking tutorial on polymorphism in c++, code seems acting strangely on call non-overriden virtual method. here classes:
// classes.cpp namespace classes { class c { public: virtual bool has_eyesight() { return false; } } c; class see : public c { public: bool has_eyesight() override { return true; } } si; }
and here main method:
// file.cpp #include <iostream> #include "classes.cpp" using std::cout; using std::endl; using classes::c; using classes::see; int main() { see& si = classes::si; cout << si.has_eyesight() << endl; c& c = si; cout << c.has_eyesight() << endl; c = classes::c; cout << c.has_eyesight() << endl; }
this code print 1 1 1
(true true true) when run; shouldn't c.has_eyesight()
return false if references c , not see?
(forgive me if sounds naive, started learning c++.)
let's go through you're doing here.
c& c = si;
c
reference classes::si
, instance of see
. vtable points of see
, , has_eyesight()
return true.
the main difference between reference , pointer can't modify target - c
point classes::si
, no matter do. meaning...
c = classes::c;
this not change reference classes::c
. cannot modify reference. instead, calls assignment operator on c, you're copying classes::c
on classes::si
. unless overload operator=
, member-by-member copy. not modify vtable, has_eyesight()
continue return true.
if want make point else, have use pointer:
see* si = &classes::si; cout << si->has_eyesight() << endl; c* c = si; cout << c->has_eyesight() << endl; c = &classes::c; cout << c->has_eyesight() << endl;
try this.
Comments
Post a Comment