How do I set a global #define in my C++ project? [closed]

This is probably a bad idea, for a few reasons:

  • Macros are potentially quite dangerous. If you #define constructor, the token ‘constructor’ anywhere in your source will be replaced by empty space, which can be quite confusing. What if you have a variable named ‘constructor’ somewhere, or attempt to make one? What if a header you include – including the standard library – has a ‘constructor’ variable or type?
  • While there are some keywords that you could put on the function that don’t affect the semantics much and could act as an indicator, those keywords do actually do something and have meaning that will confuse other people reading your code
  • If you are having trouble with the language to the point that finding constructors is hard, you are either using your IDE poorly or do not have the expertise required to use the language professionally, so marking constructors explicitly does not fix your true problem
  • There are better alternatives.

One better alternative was suggested in the comments on your question – you can just use a comment that is the same everywhere:

class Foo {
    Foo(); // constructor
};

Now you can find constructors by searching for ‘constructor’. If you want to be able to find constructors for a specific class by searching, you could do something like this:

class Foo {
    /* constructor */ Foo();
};

If you insist on doing this this is the approach I would suggest.

An alternate approach:

I don’t recommend that you do this. The comment approach should do what you want and is much less likely to mislead people reading your code or lead to unintended semantic changes. But if you insist on using a keyword, use the explicit keyword. Marking constructors as ‘explicit’ prevents you initialising an object like so: Foo f = {1, 2}, but not like so: Foo f{1, 2}. This is annoying but not fatal.

class Foo {
    explicit Foo();
}

Leave a Comment