pointer not initialized when calling the constructor

1

I'm learning c ++ concretely the 2011 standard but I can use any standard from this, my problem is that when I call car () inside the second constructor it returns the data pointer without initializing.
How can I fix it and why does this happen?

#include <iostream>

class coche
{
private:
    const int num_datos = 3;
    int *datos;

public:
    coche()
    {
        datos = new int[num_datos];
    }
    coche(const coche &nuevo)
    {
        coche(); // aqui esta mi problema
        std::copy(nuevo.datos, nuevo.datos + num_datos, datos);
    }
    ~coche()
    {
        delete[] datos;
    }
};

int main()
{

    coche nuevo_coche;
    coche *copia_coche = new coche(nuevo_coche);
    delete copia_coche;

    return 0;
}
    
asked by theriver 05.11.2018 в 22:46
source

1 answer

4
coche(const coche &nuevo)
{
    coche(); // aqui esta mi problema
    std::copy(nuevo.datos, nuevo.datos + num_datos, datos);
}

This constructor, as it is, is equivalent to this one:

coche(const coche &nuevo)
{
    coche temp = coche(); // aqui esta mi problema
    std::copy(nuevo.datos, nuevo.datos + num_datos, datos);
}

It's easy to understand now why you are not using the array datos ... you are not invoking the default constructor of your instance but you are creating a different object.

What you intend to do, which is to invoke a constructor from another, is called delegated constructors , it is a feature available only from C ++ 11 (the standard from which you are starting) and it is implemented like this:

coche(const coche &nuevo)
  : coche()
{
    std::copy(nuevo.datos, nuevo.datos + num_datos, datos);
}

Get used to this syntax because you'll see it a lot. In fact, the space that follows the colon can be used to initialize any member variable:

struct Test
{
  int a;
  std::string b;

  Test()
    : a(10),
      b("hola mundo")
  { }
};

int main()
{
  Test t;
  std::cout << t.a << ' ' << t.b;
}
    
answered by 06.11.2018 / 08:35
source