UPROPERTY - best pratices question (public, private, protected)

I have bunch of UPROPERTIES declared as public(because I need access to the from Blueprint).

But since they are public I can access to them by simply

Class->PropertyName;

And assign value by

Class->PropertyName = value.

Which honestly bothers me a bit. I need these properties to be accessible trough all blueprints (not just blueprint that derive from base class where property was declared). So Declaring them as public seem good idea in first place.

But then when I modify them in C++, I don’t have to use any Getters or Setters. I know I can just declare them anyway… But who will use them if they can just access property directly ?

My question though is. Is it good idea to declare UPROPERTIES that need to be access trough all blueprint as public, and just be careful in C++ or it is better to make them protected and create custom Getters, Setters for other blueprints to access them ?

1 Like

Make private, then use setters/getters. If you want to expose it to blueprints etc, then use the property specifiers found here.

The BlueprintReadWrite specifier may be what you want.

Caveat is that I have not tried exposing private member variables to blueprints yet myself, worth a try.

UPROPERTIES cannot be private. Though they can be protected, and protected properties are accessible across all blueprints.

This bothers me also. In Unity you can declare members as private and make them still visible in the editor.
Sure, UE is C++ and Blueprint is something totally different, but I think this should be possible. It has nothing to do with convenience but with data encapsulation and security.

Yes, they can. It would be quite troublesome if not, because there are many things you might want to hide but still keep managed. Actor components are private, for instance (or will be once the deprecation macro is applied).

What’s changed is that in UE4.7 (or was it 4.6?), the header tool will complain if you make a property both private and Blueprint accessible. The rationale behind this is that BlueprintReadOnly/BlueprintReadWrite is the blueprint equivalent of making a variable non-private, i.e.: you can access or write its value directly. This contradicts the C++ private visibility, ergo the header tool now complains.

Exceptionally, you do want to be able to do this for components (read the component but don’t write it), so the metadata keyword AllowPrivateAccess was added to shut the header tool up.

3 Likes