C++, put static constant in a class

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Hi team

I want to group a bunch of constants in a class in C++, how to I do that?
C++:
// in ver.h
class VER{
    public:
        static const MAJOR = 0;
        static const MINOR = 1;
};

// in main.cpp
#include <iostream>
#include "ver.h"

int main(int argc, char *argv[]){
    printf("ver: %u.%u\n", VER.MAJOR, VER.MINOR);
    return 0;
}
 

MrSoftware

Joined Oct 29, 2013
2,202
Pick your poison, there's a dozen ways to do it. Make them const, use #define, put them in a struct, an enum, their own class, just name them with similar names, etc.. If the goal is to store version information, you probably want that pretty front and center on a top level file, not buried down in the project somewhere. #define is commonly used, but again there are multiple ways to do it, all with their own pros and cons.
 

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Pick your poison, there's a dozen ways to do it. Make them const, use #define, put them in a struct, an enum, their own class, just name them with similar names, etc.. If the goal is to store version information, you probably want that pretty front and center on a top level file, not buried down in the project somewhere. #define is commonly used, but again there are multiple ways to do it, all with their own pros and cons.
I normally use #define or struct in C, but just wondering if there is a better way to do it in C++.
 

joeyd999

Joined Jun 6, 2011
5,285
IIRC, you can declare static objects outside the class, which are then accessible to all instances of the class.

I just pulled up a project from ca. 1995, and here is the pertinent line:

C++:
int cRoot::m_countobj=0;   //Static. Holds last handle used.
This line is located in the cRoot class source file, prior to the definition of the cRoot class.

I assume one could add const prior to the int to make it constant.
 

Marc Sugrue

Joined Jan 19, 2018
222
Hi team

I want to group a bunch of constants in a class in C++, how to I do that?
C++:
// in ver.h
class VER{
    public:
        static const MAJOR = 0;
        static const MINOR = 1;
};

// in main.cpp
#include <iostream>
#include "ver.h"

int main(int argc, char *argv[]){
    printf("ver: %u.%u\n", VER.MAJOR, VER.MINOR);
    return 0;
}
If you create the item within a class wouldn't the memory be allocated on the creation of the object? I'm not sure of the purpose of the MAJOR or MINOR constants but perhaps these should be #define MAJOR 0 & #define MINOR 1 in this case
 

402DF855

Joined Feb 9, 2013
271
I prefer enums like in the following. Note I could typedef the enum but I tend not to bother.
C:
class CMyClass {
	private:
		//
		enum {HEADER_LEN=4};
		enum {HEADER_VERSION=0};
		enum {HEADER_TARGET=1};
		enum {HEADER_BYTES=2};
		enum {HEADER_CRC=3};
		//...
	public:
		DWORD Read();
		// Read() returns one of.
		enum {
			ERROR, NODATA, SUCCESS
		};
		//...
};
 
Top