Download

Should I replicate from the base class or the derived class?

Suppose I have a base class that looks something like this:


UCLASS()
class SHOOTERCPP_API AAnimal: public AActor
{
     protected:
        UPROPERTY(Replicated)
        int16 MyAge;

        ...

}

and then I create a subclass like below where the variable is used:


UCLASS()
class SHOOTERCPP_API ADog: public AAnimal
{

       protected:
           void SetAge(int16 newAge);
        ...

}

.cpp

void ADog::SetAge(int16 newAge)
{
      // set the subclass's MyAge member
     MyAge = newAge;
}



In which class should I implement the replication function to replicate MyAge variable?


void **AAnimal**::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);

    DOREPLIFETIME(**AAnimal**, MyAge);
}

OR


void **ADog**::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
    Super::GetLifetimeReplicatedProps(OutLifetimeProps);

    DOREPLIFETIME(**ADog**, MyAge);
}

I’m still doing some testing and so far it appears that I can do this either way, but I’d really like to know what is considered best practice for something like this.

Thank you.

Do it in the class where you declare it so you don’t forget to do it in the derived classes.

You do it in the base class. If you don’t you’ll get a warning, and Super::GetLifetimeReplicatedProps adds the parent properties to the replication list anyway.