-3

Look a this basic C++ code:

#include <iostream>

class MaClasse
{
public:
    MaClasse();
    void afficher();
    void set(int valeur1,int valeur2);
    void add1(MaClasse c2);

    int _valeur1;
    int _valeur2;
};

MaClasse::MaClasse()
{
    std::cout << "Constructeur" << std::endl;
}

void MaClasse::afficher()
{
    std::cout << _valeur1 << " " << _valeur2 << std::endl;
}

void MaClasse::add1(MaClasse c2)
{
    c2._valeur1++;
    c2._valeur2++;
}

void MaClasse::set(int valeur1,int valeur2)
{
    _valeur1 = valeur1;
    _valeur2 = valeur2;
}

int main(int argc, char *argv[])
{
    MaClasse a1;
    a1.set(10,20);

    MaClasse a2;
    a2.set(30,40);

    a1.add1(a2);

    a2.afficher();


    return 0;
}

There is something i do not understand on this line:

a1.add1(a2);

As you can see, i do not pass a pointer but the object itself. When i display a2 values: They do not have changed.

But, i do not understand why the constructor is not called. a2 should be copied ?

Thanks

Bob5421
  • 7,757
  • 14
  • 81
  • 175

1 Answers1

6

A constructor is called: the copy constructor.

Since you didn't define one yourself (you only made a default constructor), the compiler made one for you. And since it made one for you, there is no std::cout line inside it to provide the evidence!

A copy constructor will be declared like this:

MaClasse(const MaClasse&);

and be defined like this:

MaClasse::MaClasse(const MaClasse&)
{
    std::cout << "Constructeur de copy" << std::endl;
}

… except you also need to make it do copy-constructory things, i.e. copy-initialising all your members.

All in, you end up with something like like:

MaClasse::MaClasse(const MaClasse& other)
   : _valeur1(other._valeur1)
   , _valeur2(other._valeur2)
{
    std::cout << "Constructeur de copy" << std::endl;
}

Incidentally, your default constructor should also be initialising those members, probably to zero.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 4
    Yeah, but your definition should also copy the members manually since there isn't a synthesized copy constructor to take care of that for you anymore. I know that you know this, but the readers of this answer might be confused – Aykhan Hagverdili Dec 17 '18 at 18:57
  • @Ayxan That's a fair observation. I'll make clear that it needs doing. Thanks! – Lightness Races in Orbit Dec 17 '18 at 23:00
  • I've added it at the end rather than altered the original copy-ctor example because I think it's a better "story" that shows how the default ctor also needs expanding from its equivalent original state – Lightness Races in Orbit Dec 17 '18 at 23:04