Problem with automatic type conversion
-
Hello.
Imagine, that I have 2 classes:
class C { private: double x; [other members] public: inline C(double const &x):x(x) {;} }; class PointerToC { private: C *p; public: inline PointerToC(C &c):p(&c) {;} }Now I want to have automatic type convertion from
doubletoPointerToC:double x; PointerToC pC(x);But it does not work. When I change reference type to const:
class PointerToC { private: C const *p; public: inline PointerToC(C const &c):p(&c) {;} }the automatic conversion works. Why? What is the difference?
Should I afraid that temporary object
Ccreated for such a conversion will be deleted just after thepCconstruction?
-
But what will happen if you try to use p later on?
-
(D)Evil schrieb:
But what will happen if you try to use p later on? ...
... boom, because your temporary object doesn't exist anymore. Don't rely so much on automatic type conversation. It is better if you have your Code under Control.
And all the inline's before your C'tor's are not necassary.
-
POD can simply be copyed ... do not need references ...
-
SAn schrieb:
class C { private: double x; [other members] public: inline C(double const &x):x(x) {;} }; class PointerToC { private: C *p; public: inline PointerToC(C &c):p(&c) {;} }; double x; PointerToC pC(x);Normally this shouldn't work too, because you try to bind a temporary C-Object to an non const-Reference