In Delphi we have an option to do a thing like this:
TClass1 = class
procedure Test; virtual;
end;
TClass2 = class(TClass1)
procedure Test; override;
end;
So in code, If I create an instance of TClass2, even if I cast the object like:
TClass1(ObjectClass2).Test;
The application will call the function declared on TClass2.
But in C/C++ I could not find a way to do this.
If I declare some void as virtual and implement the same void in the children class when I do the cast to the parent class it’ll not use the implementation of the children class.
Does anyone know how I can reproduce the behavior of Delphi in C/C++ ?
New informations:
These are my files.
---------------------- File Filho.hpp
#ifndef FILHO_HPP
#define FILHO_HPP
#include "Pai.hpp"
class Filho : public Pai {
public:
Filho();
virtual ~Filho();
void metodoX();
};
Filho::Filho() {}
Filho::~Filho() {}
void Filho::metodoX() {
std::cout << "Hello Filho!" << std::endl;
}
#endif
---------------------- File Pai.hpp
#ifndef PAI_HPP
#define PAI_HPP
#include <iostream>
class Pai {
public:
Pai();
virtual ~Pai();
virtual void metodoX();
};
Pai::Pai() {}
Pai::~Pai() {}
void Pai::metodoX() {
std::cout << "Hello Pai!" << std::endl;
}
#endif
---------------------- File Main.hpp
#include "Pai.hpp"
#include "Filho.hpp"
int main() {
Pai pai;
pai.metodoX(); //Here output the msg Hello Pai!
Filho filho;
filho.metodoX(); //Here output the msg Hello Filho!
((Pai) filho).metodoX(); //Here output the msg Hello Pai! , but here if I use the directive 'override' in Delphi, the output will be Hello Filho!. Here is my doubt.
return 0;
}
I’m not a Delphi expert, but I can explain how this stuff behaves in C++.
So in C++, you can have a class that defines a
virtualfunction, which means that if you use a base class pointer/reference to an object, that function can be invoked via dynamic dispatch (i.e. runtime function lookup).New Code You Posted
I see that you updated with your code that does this:
So when you do that, you are not using pointers/references to a base class. You are just casting the
filhoobject to aPaiobject. This does not result in a polymorphic function call, and instead will just call thePai::metodoX()function.If you did this instead:
It would call
Filho‘smetodoX()polymorphically.