I wanna have my default value!
No, there is no "direct" way in current C++ to have this "default" behaviour for built-in values.
As already answered in the two other questions, you'll need to provide the values in each constructor of MyClass.
But I REALLY need it!!!
But if you really need it, there is one way to have it indirectly: Wrapping your built-in type inside a templated class overloading its supported operators.
This way, you will be able to write the following code :
void foo()
{
bool b ; // WRONG : Not initialized
Variable<bool> bb ; // Ok : Initialized to false
int i ; // WRONG : Not initialized
Variable<int> ii ; // Ok : Initialized to 0
// etc.
}
The needed code is, for example, for bool :
template<typename T>
class Variable
{
T value_ ;
public :
Variable() ;
Variable(const T & rhs) ;
Variable(const Variable & rhs) ;
Variable & operator = (const T & rhs) ;
Variable & operator = (const Variable & rhs) ;
operator T() const ;
// define all other desired operators here
} ;
And then, coding the methods to have the desired behaviour. For example :
template<typename T>
inline Variable<T>::Variable()
: value_(0)
{
}
// For the fun, I want all booleans initialized to true !
template<>
inline Variable<bool>::Variable()
: value_(true)
{
}
// For the fun, I want all doubles initialized to PI !
template<>
inline Variable<double>::Variable()
: value_(3.1415)
{
}
// etc.
template<typename T>
inline Variable<T>::operator T() const
{
return value_ ;
}
// etc.
The list of operators can be quite great, depending on what you want to do with the variable. For example, and integer will have all arithmetic operators. And all operators are not overloadable (and should not be, in this case), so you won't have all built-in behaviours.
Anyway, as you can see, you can specialize methods for some types, if particular behaviour is desired.
Completing the list of methods, as well as correctly coding them is a very good C++ exercice.
Once done, all you need is to declare your variable :
class MyClass
{
Q_OBJECT
public:
MyClass();
~MyClass();
Variable<bool> myBool ; // it will be set to false, as defined
Variable<int> myInt ; // it will be set to 0, as defined
};
And then, you will use it as follows:
void foo()
{
MyObject o ;
o.myBool = true ;
if(o.myInt == 0)
{
++o.myInt ;
}
}
Makes sure all the code of you wrapper class is inlined and inside included header files, and you'll have no performance cost when compiled with "release" options.