Private Constructors

The methods in the Tank class were made private with the exception of AimAt(). I’m just wondering why having a private constructor works. From my understanding, a private constructor implies that the constructor can only be called from within the class itself, not outside yet we are capable of creating instances of the Tank pawn in Unreal. When making things public, private, or protected, do we only consider it within the scope of the code itself and not when using blueprints or in the unreal editor (with the exception being when we’re using UPROPERTY)?

I’m not really sure what happens when blueprints extend the classes we make in C++, but there are a lot of scenario’s where it might be useful to have private constructors.

Singleton pattern
For instance, this pattern makes sure that the constructor of your class cannot be called by another class because we only want 1 instance of the class to exists during the program’s execution. This requires us to use static functions to get the instance when we want to use it.

Factory methods
When using factories, it could be that the class is instantiated by a factory, instead of the class itself. This means that there will be special classes and method to create the object we want. This could also entail a private constructor.

Unreal Engine 4
When it comes down to UE4, these 2 cases do not really apply out of the box. As a general rule of thumb though, private methods can be accessed by friends of the class. A friend can access private members and functions of a class it’s declared to be a friend off. I’m also not entirely sure this is the case with blueprints.
What I am certain of, is that the AMyActor.generated.h contains some hints as to what the blueprints do with your class.

#define BattleTank_Source_BattleTank_Pawn_Tank_h_12_STANDARD_CONSTRUCTORS \
	/** Standard constructor, called after all reflected properties have been initialized */ \
	NO_API ATank(const FObjectInitializer& ObjectInitializer); \
	DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ATank) \
	DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ATank); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ATank); \
private: \
	/** Private move- and copy-constructors, should never be used */ \
	NO_API ATank(ATank&&); \
	NO_API ATank(const ATank&); \

As you can see, a bunch of other constructors are being generated for you, without you ever seeing them in your own .h and .cpp files. I think it’s fair to assume that blueprints will try to use these constructors instead of the ones we declare without actual arguments in them, for instance ATank().

A cool test case could be to override or reimplement the ATank(const FObjectInitializer& ObjectInitializer); method in your .cpp file to see if it gets called when a blueprint instantiates your Tank class.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms