Empty constructors in C ++:

In my code, I do the following, but I'm not sure if I am “allowed”, or if this is a good design technique. I need to create an empty constructor, but I also need a constructor that initializes the variables specified by the parameters. So I do the following:

This is a Ch 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;
  }

Am I trying to declare an empty constructor correctly or do I need to set A = NULL and B = 0.0?

+6
source share
7 answers

Your empty constructor does not do what you want. A data item will doublenot be initialized to zero unless you do it yourself. std::stringwill be initialized with an empty string. Therefore, the correct default constructor implementation will be simple

C::C() : B() {} // zero-initializes B

, :

C::C(const string& a, double b) : A(a), B(b) {}

, , .

+9

, , undefined. string - , , double ( defualt), undefined ( ).

+4

A std::string, NULL, , std::string , .

C::C()
:B(0.0)
{
}

, ?

C(const string& a= "", double b= 0.0)
: A(a),
  B(b)
{
}
+2

, , , . , , . , B 0, , "" .

+2

. , string, double. , string foo; .

, :

class Bar{
    private:
        Bar(); //Explicitly private;
};
Bar b;

Bar::Bar().

: , , . , . , , , , , - , .

+1

, , . , . - , , .

, :

C::C(string a, double b):A(a), b(b)
{
}
0

In C ++ 11 and later, you can use the following to generate the default constructor without parameters:

C() = default;

This is more accurate than C () {}.

This does not initialize the participants. In C ++ 11, you can initialize elements in a single line of declaration:

int m_member = 0; // this is a class member

These 2 functions eliminate the need to create your own constructor without parameters to initialize the default members. Thus, your class may look like this when applying these two functions:

class C
{
private:
    string A;
    double B = 0;

public:
   C() = default;
   C(string, double);  
}
-1
source

All Articles