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.