package Point;
use Moose;
has 'x' => (isa => 'Int', is => 'rw');
has 'y' => (isa => 'Int', is => 'rw');
package Point3D;
use Moose;
extends 'Point';
has 'z' => (isa => 'Int', is => 'rw');
package main;
use Data::Dumper;
my $point1 = Point->new(x => 5, y => 7);
my $point3d = Point3D->new(z => -5);
$point3d = $point1;
print Dumper($point3d);
Is it possible to cast a parent to child class such as c++? In my examble is $point3d now a Point and not a Point3D include the Point.
Take a look at the Class::MOP documentation on CPAN, especially the clone_object
and rebless_instance
methods:
sub to_3d {
my ($self, %args) = @_;
return Point3D->meta->rebless_instance(
$self->meta->clone_object($self),
%args,
);
}
And then use it like the following:
my $point_3d = $point->to_3d(z => 7);
This will also take care to treat the newly specified %args
as if they've been passed in by the constructor. E.g. builders, defaults, and type constraints are all considered during this build.
You do not need to cast in Perl, since it is a dynamic language. In your case though, the variable $point3d
contains a reference to a Point
object at the end of the script. You cannot treat this as a Point3D
because it is not a Point3D
. You could manually convert it, but you can't "remake" an existing object as a different class. (Well, you theoretically can in Perl, but you shouldn't.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With