-3

I wrote a class B as a subclass of A to extend it. And now I want to change all the

 a = A::create(); 

to

 a = (A*)B::create(); 

And everything works fine. But I don't want to manually change the code wherever an object of A is created. So I tried the following #define directive

#define A::create (A*)B::create

but it doesn't work at all. I don't know what the problem is. Any help? Can I use #define directive with :: ? Why it doesn't work?

Chen.so
  • 173
  • 7
  • You shouldn't need the cast, assuming `B` really is a subclass of `A` and `B::create()` returns `B*`. And you really should change the code if it needs changing, not leave future debuggers wondering why `A::create` does something other than create an `A`. – Mike Seymour Oct 23 '14 at 16:24
  • I would strongly advise against trying to solve the problem this way - if you need to change the code everywhere, it's probably best to directly change the code everywhere or find some way of introducing another level of indirection. – templatetypedef Oct 23 '14 at 16:25
  • 2
    If _every_ call to `A::create` must be changed, why not just change what `A::create` does? And in any case, avoid C-style casts. – David K Oct 23 '14 at 16:27
  • And if `B` is a derived type of `A`, and if `B::create()` returns a `B*` then you don't even need the cast -- conversion from pointer-to-derived to pointer-to-base is implicit. – cdhowie Oct 23 '14 at 16:28

2 Answers2

6

The problem is quite simply that you can't use those characters in a macro name; they aren't allowed because the standard says they aren't.

Macro names can only contain letters (upper and lowercase), underscores, and digits. (Additionally, they can't start with a digit, and macro and identifier names starting with an underscore followed by an uppercase letter are reserved for use by the compiler and the standard library.)

If you use other characters like colons and parens then you just don't have a valid macro name.

Further reading:

Community
  • 1
  • 1
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

A macro name must be a single identifier. A::create is an identifier, followed by a coloncolon token, followed by another identifier. So it doesn't recognize your syntax.

That aside, what you're doing is a really, really bad idea. Use a regex-capable search&replace instead.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157