2
I have a parent class/structure and a daughter class/structure in C++. The parent class defines a method, and the daughter class burdens that method.
Trivial example:
struct Pai {
void imprimir() {
std::cout << "Classe pai" << "\n";
}
};
struct Filha : Pai {
void imprimir() {
std::cout << "Classe filha" << "\n";
}
};
I want to declare a variable of type Pai
, this variable can be initialized with a Pai
, or any other class inheriting the same:
Pai obj = Filha{};
My problem occurs in invoking the method of that instance. In languages like Java or C#, it is expected that the method invoked is the one belonging to the instance of the class stored in the variable "obj", that is, it should print "Child class".
But in C++ what happens is that the program invokes the method of the same class as the variable is declared, invokes the class method Pai
, printing "Parent class".
There is something I can do so that when invoking the "print" method, the method declared in the child class is invoked?
Here has code running for better viewing.
I am particularly concerned with the destructor method, it is possible to declare this "override" in the destructor class Daughter also?
– Bruno
That is another question, but it can, and in many cases it must if it is necessary. I am only afraid of a destructor in a kind by value.
– Maniero
Well, "smart pointers" implement destructors even though they’re a guy by value, right? The example I gave was used only to avoid polluting the question.
– Bruno
That’s why I’m afraid and not that it’s forbidden. It is very rare to be useful, almost always will be an invention without the person understanding why is doing it. The smart Pointer, should not be inherited. The problem of programming is that everything can be composed, what is beautiful alone does not work with other things. Join destructor polymorphism in type that should be by value but the object was created with reference to work...
– Maniero