Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty Constructors in C++:

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?

like image 274
FranXh Avatar asked Feb 17 '13 04:02

FranXh


1 Answers

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.

like image 118
juanchopanza Avatar answered Sep 30 '22 15:09

juanchopanza