• 0

[C++] How to return an enumeration?


Question

Hey all, having a bit of trouble here. I've been trying to read and understand other guides on the internet, but they either get way too complex for my fairly simple problem, or they don't solve the problem at all. Basically, I'm trying to create a get method for an enumeration.

enum getGameState() {return eGameStateCurrent;}

I've declared this in the .h file, by the way. When I compile it, I get this error:

  Quote
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

So, I try to change the type, and after a bit of research I try using a const enum return type instead:

const enum getGameState() {return eGameStateCurrent;}

Still though, same error. I've also tried just "const" type, and same thing. I don't fancy using an int, because that would mean I'd have to explain what each enumeration value is when calling upon the accessor, unless there's a way of using an int without having to do all of that.

So, how do I go about returning an enumeration?

Thanks in advance.

Link to comment
https://www.neowin.net/forum/topic/669646-c-how-to-return-an-enumeration/
Share on other sites

7 answers to this question

Recommended Posts

  • 1

Enum itself is not a type, it defines a type much like struct / class do. First, you have to define an enumerator.

// Define Enumerator
enum GameState{ Zero, One, Two, Three, Four };

// Define value
GameState eGameStateCurrent = GameState.One;

// Get value
GameState getGameState(){
	return eGameStateCurrent;
}

// Set value
void setGameState(GameState value){
	eGameStateCurrent = value;
}

Hope this helps.

  • 0
  Xinok said:
Enum itself is not a type, it defines a type much like struct / class do. First, you have to define an enumerator.

// Define Enumerator
enum GameState{ Zero, One, Two, Three, Four };

// Define value
GameState eGameStateCurrent = GameState.One;

// Get value
GameState getGameState(){
	return eGameStateCurrent;
}

// Set value
void setGameState(GameState value){
	eGameStateCurrent = value;
}

Hope this helps.

First of all, thanks for the quick reply. Secondly, I'm defining the enumeration in header, not in the main cpp file, meaning I can't define the enumeration.

GameState.h

public:
	eGAMESTATE getGameState() {return eGameStateCurrent;}

protected:
	enum eGAMESTATE
	{
		eGameStateMenu,
		eGameStateInstruc,
		eGameStateCredits,
		eGameStatePlay,
		eGameStateGmWin,
		eGameStateGmOver
	};

	eGAMESTATE eGameStateCurrent;

However, it still throws me the same error (actually, it throws an extra one, about me needing a ";" before getGameState, but this is obviously due to it not liking eGAMESTATE). Is there a way around this? I really need the enumeration to be a protected attribute.

  • 0

As Xinok said ... enum doesn't create an actual *type*. To return from a function, you'll need an actual type. Just use typedef to create a type for your enum.

#include <iostream>

class EnumTest {
  protected:
	typedef enum eGAMESTATE {
	  eGameStateMenu,
	  eGameStateCredits,
	  eGameStatePlay
	} GAMESTATE;

	GAMESTATE m_GameStateCurrent;

  public:
	EnumTest() : m_GameStateCurrent(eGameStatePlay) {
	}

	GAMESTATE GetGameSate(void) {
	  return m_GameStateCurrent;
	}
};

int main(void) {
  EnumTest eTest;

  return eTest.GetGameSate();
}

  • 0

Having the enumerated type protected, when you have a public method which returns a value of that type, defeats the purpose of enumerating it; the type cannot be accessed outside of the class, meaning you cannot compare the result of the method to the enumerations. Sure, you can check the integral value of it, but it's the difference between having, for example, if (obj.GetGameState() == 2) versus if (obj.getGameState() == ExampleClass::eGameStatePlay) in code which makes use of that public method.

Edited by David Scaife
  • 0

Tareq, you legend, you got it working for me! Thank you! It appears I definitely have a lot, lot more to learn about C++.

However, I've now run into another issue :( You see, the whole reason why I was doing this is so I can grab the value of one enumeration from CGameState and make it the same value in CGame's enumeration.

CGame.h

private:
	typedef enum eGAMESTATE
	{
		eGameStateMenu,
		eGameStateInstruc,
		eGameStateCredits,
		eGameStatePlay,
		eGameStateGmWin,
		eGameStateGmOver
	} GAMESTATE;

	GAMESTATE eGameStateCurrent;

CGameState.h

protected:
	typedef enum eGAMESTATE
	{
		eGameStateMenu,
		eGameStateInstruc,
		eGameStateCredits,
		eGameStatePlay,
		eGameStateGmWin,
		eGameStateGmOver
	} GAMESTATE;

	GAMESTATE eGameStateCurrent;

As you can see, exactly the same. I've made a set method (which works!), but I get this error:

error C2664: 'CGameState::setGameState' : cannot convert parameter 1 from 'CGame::GAMESTATE' to 'CGameState::GAMESTATE'

Considering it has the same type defined in both enumerations (with both enumerations having the same items), shouldn't it just gel? How would I go about getting the value defined from CGameState's eGameStateCurrent enumeration and setting it to be the value for CGame's eGameStateCurrent enumeration?

EDIT: Just read your post David. I see what you mean, but in this case I'm just trying to share between two enumerations with the same values. Surely that still doesn't defeat the purpose, right?

EDIT: I have absolutely no idea why I'm attempting it this way. I have this tendancy to go about things in a rather weird manner and then end up with situations like these! Haha...

I'm going about it a different way, and this way (if I've got everything right), should go ahead without a hitch. Thank you all for your help, though! You've definitely taught me more :)

Edited by The Tjalian
  • 0

If you want to use the same enum, it has to be the SAME enum, not two enums that have the same name... As the compiler points out, CGame::eGAMESTATE and CGameState::eGAMESTATE are two different types and are not convertible to one another. You could force it with a cast but that would be just stupid. The clean solution is to declare that enum in ONE place, and then #include the file containing it whenever you need to use its definition.

For instance if eGAMESTATE is part of CGame, and CGame is in CGame.h, then if you want to use eGAMESTATE in class CGameState, you need to #include "CGame.h" in CGameState.h and reference eGAMESTATE using the fully qualified CGame::eGAMESTATE.

I hope that makes sense.

BTW, in C++, enums already are types, so you don't need to typedef an artificial one. Unless you're writing code that needs to be compatible with C, not your case since you are using classes.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I believe voice assistants have reached a dead end in terms of usability. You can only do so much with voice. Even Google is sidelining Google Assistant for Gemini. Once you can no longer shoehorn "AI" everywhere, the industry will move on to the next fancy trend try to push voice assistants to use that tech.
    • Gemini in Google Sheets can now generate fully editable charts by David Uzondu Back in January, Google introduced a feature in Google Sheets powered by Gemini that lets you ask the AI to create charts from your data. The problem was, these charts were just static pictures, slapped on top of your cells. You could not edit them, and they would not update if your data changed. Now, the company has upgraded the feature so you can edit the charts however you want, plus they stay synced with your data as it changes. The process is quite straightforward. You use the Gemini side panel and just type what you want, like "create a bar chart showing campaign performance by market." Gemini then builds the chart, and when you insert it, the chart appears in a completely new tab within your spreadsheet. From that new home, you have total control. You can change the title, tweak the colors, and adjust all the little details just like any normal chart you would build yourself. It is not a completely perfect system, however. The biggest catch is that the editable chart is linked to the data in that new tab, not your original data source. So if you want the chart to reflect new numbers, you have to update the data in the chart’s dedicated tab. This is a bit of a weird detour from how standard Sheets charts have always worked, where they update directly from the source cells. For certain, more complex chart types, Google also notes that Gemini might still fall back to spitting out a static image, so your mileage may vary. The full rollout began recently, with Google expecting it to reach everyone within one to three days. This update is available for a bunch of Google Workspace accounts, including Business Standard, Business Plus, Enterprise Standard, and Enterprise Plus. It is also included for anyone with a Google One AI Premium plan, which the company has since renamed to Google AI Pro and Ultra. If you are on one of the old Gemini Business or Enterprise add-ons that Google stopped selling back on January 15, 2025, you get this feature too. Just make sure your admin has the "Smart features and personalization" setting turned on, or none of this will work.
    • iOS feature updates are lacklustre. I know it’s difficult with a mature OS, but imagine the announcements without Liquid Glass. Pretty thin.
    • Should you buy the Kindle Scribe? What to know about Amazon's e-reader for notes and reading by Paul Hill We’re all familiar with the Amazon Kindle lineup of affordable e-readers, but did you know that Amazon has a Kindle for writing on too? That’s where the Kindle Scribe comes in. The Scribe is more notebook sized, rather than book sized and has the largest screen Amazon has ever included in a Kindle. With this device, Amazon is trying to expand the paper reading-like experience to paper writing-like. With the current discount, you can save up to 25%, with prices as low as $299.99. There are three models available: a 16GB, 32GB, and 64GB model. You cannot expand the storage so be sure to pick the size you’ll need from the get-go. The Kindle Scribe won’t be the perfect choice if all you want to do is read books, however, if you’re a student or professional who wants to take notes, or an avid reader that wants to make annotations, then this could be a good pick for you. What it does The Kindle Scribe features a large 10.2-inch glare-free display with a 300 ppi density. It comes with a Premium Pen that makes it feel like you’re writing on paper as you jot down your notes. To make writing easy, you get Active Canvas for in-book notes and a built-in notebook with templates. You can import and write on PDFs and documents via Send to Kindle, including sending directly from Word if you have a Microsoft 365 subscription. Once you have written out your notes, the Kindle Scribe allows you to summarize them using artificial intelligence. You can even customize the length and tone of your notes. You can also refine your notes by converting your handwritten words into a script font. One of the standout features of other Kindle devices is their spectacular battery life, and the Kindle Scribe promises the same. The battery will last you up to 12 weeks for reading and up to 3 weeks for writing. Furthermore, Amazon has used 18% recycled materials including 100% recycled aluminum parts, and it comes in fully recyclable packaging. Finally, and it shouldn’t really need mentioning, the Kindle Scribe has full access to the Kindle Store so you can quickly and easily gain access to all of the latest books. Should you buy it? If you are looking for a distraction free gadget to read books on and take notes then the Kindle Scribe is definitely worth considering now that it is at its lowest price to date. Students and professionals are two groups who might benefit the most from this model. If you’re just looking for a Kindle for reading on Amazon, there are other models that may be better such as the Paperwhite or Oasis. The Kindle Scribe is a pretty radical change for a Kindle device with its very large display and writing capabilities. If you’ve been waiting for something like this, then it may justify an upgrade from an older Kindle. If you do decide to buy, make sure to get enough storage from the get go. Amazon Kindle Scribe (16GB): $299.99 (Amazon US) / MSRP $399.99 Amazon Kindle Scribe (32GB): $319.99 (Amazon US) / MSRP $419.99 Amazon Kindle Scribe (64GB, Tungsten): $349.99 (Amazon US) / MSRP $449.99 Amazon Kindle Scribe (64GB, Metallic Jade): $349.99 (Amazon US) / MSRP $449.99 This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • Week One Done
      IAMFLUXX earned a badge
      Week One Done
    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
    • First Post
      Kurotama earned a badge
      First Post
    • Collaborator
      Carltonbar earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      506
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      241
    4. 4
      +Edouard
      201
    5. 5
      snowy owl
      163
  • Tell a friend

    Love Neowin? Tell a friend!