In this code the constructor is called twice.
How do I avoid that?
If I uncomment the default constructor code block then code does not give satisfactory output..
And I also want conditional based instantiation of template so I used void pointer.
#include<iostream.h>
template<class Type>
class Data{
public:
Type val;
Data(Type v){
cout<<"In Constructor Param";
val = v;
}
Data(){
// cout<<"In Constructor Defa"; uncommnet this line
}
~Data(){}
};
int main(){
Data<void *> obj;
obj = new Data<float>(31.34f);
cout<<*(float*)obj.val;
}
Output:
In Constructor Param
In Constructor Param
31.34
Thanks for involving.
Because you are creating three objects. Your code contains an implicit conversion from
Data<float>*toData<void*>, via the conversion constructorData<void*>::Data(void*), and is equivalent toI’ve no idea how to avoid that, because I’ve no idea what your code is trying to do. You could prevent weird conversions like that by declaring the constructor
explicit, so that it doesn’t allow implicit conversions.Also, whichever book you’re using to learn C++ is very outdated. Since 1998 (and possibly earlier), the standard I/O header has been called
<iostream>with no.h, and all the standard library’s names likecouthave been innamespace std.