Download

Simple Constructor

Hi,

I’m from a Java background so I’m not used to the idea of 2 files (main and header) for one thing.

I have a base class called Depletable, which items such as a water tank, fuel can etc will inherit from, and includes properties such as capacity and amount along with methods to manipulate them.

The message log keeps throwing errors indicating incorrect syntax. Trying to fix it has taken around 4 hours and is driving me insane.

Depletable.cpp:



// Fill out your copyright notice in the Description page of Project Settings.

#include "NocturnalSynergy.h"
#include "Depletable.h"

UDepletable::Depletable(unsigned int capacity)
{
	UDepletable::capacity = capacity;
	UDepletable::amount = capacity;
}


Depletable.h:



#pragma once

#include "Depletable.generated.h"

UCLASS()
class UDepletable : public UObject
{
	GENERATED_UCLASS_BODY()

private:
	unsigned int capacity;
	unsigned int amount;

public:
	Depletable(unsigned int capacity);

	unsigned int getCapacity()
	{
		return capacity;
	}

	unsigned int getAmount()
	{
		return amount;
	}
};


Thanks,

Rix

First things first, the constructor should reflect the name of the class (your constructor should be UDepletable(), don’t forget that the U it’s just a UE4 standard for UObject-derived classes, c++ still requires the full name).
Then replace GENERATED_UCLASS_BODY() with GENERATED_BODY().

Unfortunately Unreal doesn’t allow you to have a custom constructor, you’ll have to use an initialization function:


UCLASS()
class UDepletable : public UObject
{
	**GENERATED_BODY()
**
private:
	unsigned int capacity;
	unsigned int amount;

public:
	/** Default constructor */
	**U**Depletable(/*Empty*/);

	/** Init class */
	void Init(uint32 InCapacity);

.cpp


UDepletable::**U**Depletable()
{
	// Put some default values

	capacity = 100U;	// The namespace is not required in order to access member variables inside a member function
	amount = capacity;
}

/** Init class */
void UDepletable::Init(uint32 InCapacity)
{
	capacity = amount = InCapacity;
}

EDIT: just to be clear, you can have a custom constructor for plain c++ classes, but not for UObject-derived classes

Awesome, that works! Thanks! :3