Knowing which class of daughter the parent class points to

Asked

Viewed 277 times

3

I came from Java and I have a question about polymorphism in C++.

Given these classes:

class Empresa{
vector<Pessoa> pessoas;
int empregados;
addPessoa(Pessoa* p)
}

class Pessoa {
...
};


class Empregado:public Pessoa{
...
}

class Dono:public Pessoa{
...
}

e a função:

addPessoa(Pessoa* p){
pessoas.push_back(*p);
if(...) // pessoa é um empregado
empregados++;
}

I’m not getting to implement this if.

  • I don’t know much about C++, but I do know that most solutions in this regard are based on the use of dynamic_cast. In other words, you would try to transform p in a new class object Empregado and test if the pointer is not null.

  • What is an employee? Is that a concept represented in the code? I’m just seeing "employee". It’s the same thing?

  • Polymorphism is not using if. The idea of polymorphism is that you simply make the call of a function and the correct implementation be called based on the type.

1 answer

4


The solution for this is equal to Java, if the function should add a Empregado then make the function receive this and not the general class. As for the other positions.

addEmpregado(Empregado* p) {
    pessoas.push_back(*p);
    funcionarios++;
}

I put in the Github for future reference.

Who will call the function knows what type of object it is, so it is she who must decide what to call.

I will not get into the merit that this inheritance may not be suitable. There is a long time inheritance abuse.

  • very good the 'debate' link. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.