1
There is a class as below:
class vetor
{
protected:
int x, y;
public:
//Construtor
vetor(int _x=0, int _y=0);
};
and another:
class pos : public vetor
{
public:
//Construtor
pos();
umaFuncaoQualquer(int _x=0, int _y=0);
outraFuncaoQualquer(int _x=0, int _y=0, bool algo=false);
maisUmaFuncaoQualquer(void);
};
I want to do this:
vetor v(1, 3);
pos p;
p = v;
How would I do that in c++? Would I need to create a function for that, or am I thinking wrong?
Up 1:
I managed to do it this way, in the vector class:
class vetor
{
protected:
int x, y;
public:
//Construtor
vetor(int _x=0, int _y=0);
//Retorna x
int getX(void);
//Retorna y
int getY(void);
};
in the pos class:
class pos : public vetor
{
public:
//Construtor default
pos();
/*
Construtor para receber o vetor. É responsável por atribuir a x e y
herdados pela classe vetor o x e y de uma instância vetor atribuída,
utilizando as funções getX e getY da classe vetor,
que pega o x,y que estão protected na mesma.
Sua implementação:
pos::pos(vetor _v)
{
x = _v.getX();
y = _v.getY();
};
*/
pos(vetor _v);
umaFuncaoQualquer(int _x=0, int _y=0);
outraFuncaoQualquer(int _x=0, int _y=0, bool algo=false);
maisUmaFuncaoQualquer(void);
};
with that the code below works:
vetor v(1, 3);
pos p;
p = v;
However I would like to know other ways to do the same, maybe there are ways that fit better in this situation. And I didn’t understand very well why it works this way and not the first way if they both have x and y. I remember reading about it once:
//Funciona sem precisar do construtor de cópia
v = p;
//Apenas funciona se tiver um construtor de cópia
p = v;
I read it like that, but I can’t remember why?
Up 2:
Referring to @Ossetian_odin’s reply, I’m still not understanding some points, I’ll start from top p low:
1 - Regarding the use of Friend, it would not be necessary in the case of my example, because the members of the class "vector" are protected and not private, so they can already be accessed by the derived class. And the copy constructor that the compiler declares, is in the class itself receiving the class itself, as I want to assign a different one, requires me to create a constructor for that, the problem is that I created in the class "pos" and not in the "vector", which is somewhat confusing, but it could not be the opposite, since following the logic "is one", "vector" is not a "pos", but "pos" is a "vector". I’m sure?
2 - As for "downcasting", you say to create an abstract class, so would I create the "vector" class as abstract? Wouldn’t it be better to use "dynamic_cast" in this case? And if I use "dynamic_cast" what happens when I do "dynamic_cast < pos * > (&v);", p will have all the variables and functions of "pos"(since it inherits "vector", are those of "vector" and those that only exist in "pos"), receiving the assignment of v the variables that have in common, or p will have only what "vector" has?
Up 3:
I studied it, and I realized the way I Up 2 is the right one for this case, at least the most certain I’ve found so far. Because what I want to do is to assign a "vector" object to a "pos" object in the most "abstract" way possible, abstraction for another person who will use, it is easier to do "p = v;" than "static_cast(&vet);" for example; what I need is not a "downcasting", and not to use polymorphism, but I appreciate both responses that made me study these concepts further, because what is really needed in this case is simply to assign "p = v", where p having a constructor to handle the assigned class will work, it’s not conversion(Polymorphism) It needs a copy. I read about a material I found in Google, and in the chapter "Pointer Conversion" explained to me:
https://webserver2.tecgraf.puc-rio.br/ftp_pub/lfm/CppBorgesClinio.pdf
Translating for the variables of the question:
vetor v, *pv; // pv pode apontar para objetos do tipo vetor e derivados
pos p, *pp; // pp pode apontar para objetos do tipo pos e derivados
v = p; // copia v parte vetor de p para v (não é conversão)
p = v; /* erro! v pode não ter todos elementos para a cópia(A questão se
refere a este caso, que também não é conversão, e pode ser
resolvido da maneira do Up 2, o que queria saber era se existe
outras maneiras alem da que fiz no Up 2, que seria para cópia,
e não mudança de forma ou tratar um classe como uma
diferente)
*/
pv = &v; // ok
pv = &p; // ok, pv aponta para um objeto do tipo pos
pp = pv; // erro! pv pode apontar para um objeto do tipo vetor
pp = &p; // ok
pp = &v; // erro! pp não pode apontar para objetos do tipo vetor
And because when I create a works constructor, I wouldn’t be assigning?
– PerduGames
Is there a way to put a code snippet with doubt? Type
gato xaninho = new urocordato()
?– Jefferson Quesado
An example of the constructor in Up 1 is in the question.
– PerduGames
But what he was asking using his serial example something like this: why
animal bixo = new gato();
works in C++, butgato gatinho = new animal();
doesn’t work? but it works if I create a copy builder to handle the members of "animal" and assign them to the members of "cat"?– PerduGames
@I’ll study before I update my answer. It seems that if he creates a constructor that receives an object and tries to assign that object to his, he knows how to do the coercion
– Jefferson Quesado
I think it’s called a copy builder, but I’ve never quite understood how C++ handles it.
– PerduGames
@Perdugames, copy builder I remember in another scope, but anyway. I did the example: http://ideone.com/ir5d46. I will update my answer
– Jefferson Quesado