Passing objects by reference c ++

1

Speak, I'm trying to learn a little bit of C ++ and I have a question regarding the passing of objects to a class and manipulating it within it. I can do this in C #, but I'm trying in C ++ without having much success.

Example: c #

class Folha
{

    public void Marcar()
    {
       ...
    }

}

class Papel 
{

    Folha f;

    public Papel(Folha folha_)
    {
        f = folha_;
    }

    public void MarcarFolha()
    {
        f.Marcar();
    }
}

void main()
{

    Folha folha = new Folha();
    Papel papel = new Papel(folha);
    papel.MarcarFolha(); 

}

Is this kind of approach possible in c ++ ??? If yes, how to implement?

    
asked by anonymous 11.11.2017 / 01:43

1 answer

2

To do the same in C ++ it is common to pass a pointer to the object in the class constructor.

The same example could be coded like this:

class Folha
{

public:

    void Marcar(){
        cout<<"Marcar de folha";
    }
}; /*<--- ; é necessário em c++*/

class Papel
{
    Folha *f; //guardado como ponteiro

public:

    Papel(Folha *folha_){ //recebe ponteiro
        f = folha_;
    }

    void MarcarFolha()
    {
        f->Marcar(); //acede com -> por ser ponteiro
    }
};

int main()
{
    Folha folha; //cria objeto de forma estatica
    Papel papel(&folha); //passa o seu endereço
    papel.MarcarFolha(); //escreve Marcar de folha

    return 0;
}

See the Ideone example

Notice the differences carefully. Only the word public has been written once and everything that is down there is public. Folha was saved as pointer in class Papel .

Of course I could also do main with new similar to what you have in C #, like this:

void main()
{
    Folha *folha = new Folha(); //ponteiro
    Papel *papel = new Papel(folha); //ponteiro também
    papel->MarcarFolha(); 
}

But this forces you to release objects with delete when you do not need them, which becomes more difficult to manage. For this reason you should give preference to the first form that I presented

Using C ++ reference passing

class Folha
{

public:

    void Marcar(){
        cout<<"Marcar de folha";
    }
}; 

class Papel
{
    Folha f; //guardado sem ser como ponteiro

public:

    Papel(Folha &folha_){ //recebe a referência
        f = folha_;
    }

    void MarcarFolha()
    {
        f.Marcar(); //acede agora com . porque não é ponteiro
    }
};

int main()
{
    Folha folha; //cria objeto de forma estática
    Papel papel(folha); //passa normalmente
    papel.MarcarFolha();

    return 0;
}

Example also in Ideone

Internally the reference is treated as a pointer in the method where it was used. Note however that in the latter case the sheet received in the constructor will be copied to the field of the class named f , which will be different from the folha that had in main . The same does not happen in the previous examples, and I suspect that this was not the behavior I intended.

    
11.11.2017 / 02:21