In my code I am doing the following, but I am not sure if I am "allowed" to or if it is a good designing technique. I need to create an empty constructor, but I also need a constructor that initializes the variables given the parameters. So I am doing the following:
This is the C.h file.
class C
{
private:
string A;
double B;
public:
//empty constructor
C();
C(string, double);
}
And my C.cpp file:
//this is how I declare the empty constructor
C::C()
{
}
C::C(string a, double b)
{
A = a;
B = b;
}
Is the way I am declaring the empty constructor right or do I need to set A= NULL and B=0.0?
Best Answer
Your empty constructor does not do what you want. The
double
data member will not be zero-initialized unless you do it yourself. Thestd::string
will be initialized to an empty string. So the correct implementation of the default constructor would simply beConcerning the other constructor, you should prefer the initialization list:
otherwise, what you are doing is an assignment to default constructed objects.