i trying write interface variable value. base class provides enum field, type of variable stored (like int, char, etc...) , virtual functions. classes inheriting interface should implement representation of variable type each.
#include <iostream> enum type { int, char }; class var { type type; public: var(type t): type(t) {} virtual void printvalue() { std::cout << "-\n"; } virtual void printtype() { std::cout << type << std::endl; } }; class intvar : public var { int value; public: intvar(int i): var(int), value(i) {} void printvalue() { std::cout << value << std::endl; } }; class charvar : public var { char value; public: charvar(char c): var(char), value(c) {} void printvalue() { std::cout << value << std::endl; } }; then tried this:
var* np = new intvar(1); np->printtype(); np->printvalue(); np = new charvar('a'); np->printtype(); np->printvalue(); the output was
0 (type::int), 1, 1 (type::char), a
so worked expected, when tried same references, outcome bit strange.
var& nr = *(new intvar(1)); nr.printtype(); nr.printvalue(); nr = *(new charvar('a')); nr.printtype(); nr.printvalue(); here output
0 (type::int), 1, 1 (type::char) , 1
why did code work, when using pointers , didn't work references? or overlook obvious errors?
the solution using pointers makes nr point intvar @ first, , charvar.
the solution using references creates intvar object, creates new name (nr) object , changes values of object based on values of charvar.
references cannot rebased did pointers. reference references same object throughout lifetime.
Comments
Post a Comment