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?
Your empty constructor does not do what you want. The double
data member will not be zero-initialized unless you do it yourself. The std::string
will be initialized to an empty string. So the correct implementation of the default constructor would simply be
C::C() : B() {} // zero-initializes B
Concerning the other constructor, you should prefer the initialization list:
C::C(const string& a, double b) : A(a), B(b) {}
otherwise, what you are doing is an assignment to default constructed objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With