3

I am looking for way to Declare and Initialize a constant struct in my Class Header file. The class is being used by an MFC app, as you can see. The layers on my MFC Dialog will never change, so I would like to delcare them constantly.

I am looking for something like this:

class CLayerDialog : CDialogEx { ... public: const LAYER_AREA(CPoint(0, 70), CPoint(280, 140)); } 

The struct:

struct LAYER_AREA{ CPoint topLeft; CPoint bottomRight; }; 

What is the best way to do this, to save as much performance as possible and to easily maintain the layers?

3
  • What are you actually asking? Commented Aug 30, 2014 at 22:04
  • So you want the LAYER_AREA to be const in each object or you want it to be the same single object available in all the objects of CLayerDialog? Commented Aug 30, 2014 at 22:09
  • I want it to be the same single object of CLayerDialog. Which always stays the same, yeah Commented Aug 31, 2014 at 11:04

2 Answers 2

3

Do you mean a static const member variable?

// header file class CLayerDialog : CDialogEx { /* ... */ public: static const LAYER_AREA myvar; }; // source file const LAYER_AREA CLayerDialog::myvar(CPoint(0, 70), CPoint(280, 140)); 

Note that the variable must be defined out-of-line (in the source file rather than the header file). You'll also need an appropriate constructor for struct LAYER_AREA as well.

Sign up to request clarification or add additional context in comments.

3 Comments

This was true in C++03, and probably still the best approach for Visual C++, although the next version ought to have better support for brace-or-equal-initializer syntax.
Alright, so there I will have to use the CPP file for that?
@Future: Yup, the CPP "source file".
1

You can do something like this: ( I have made a few assumptions about the classes you had not provided )

in header file

class CDialogEx { public: CDialogEx (){} }; class CPoint { public: CPoint ( const int& _x, const int& _y ):x(_x), y(_y){} private: int x; int y; }; struct LAYER_AREA { CPoint topLeft; CPoint bottomRight; LAYER_AREA ( CPoint tl, CPoint br ): topLeft ( tl ), bottomRight ( br ) { } }; class CLayerDialog : CDialogEx { public: CLayerDialog (); const LAYER_AREA myStructVar; }; 

in .cpp file

CLayerDialog::CLayerDialog() : myStructVar ( CPoint(0, 70), CPoint(280, 140) ) { } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.