2

I've stumbled upon code using the following syntax.

int main(){    
  class foo{
    public:
      int x;
      foo(int y){x=y;}
  }
  * bar = new foo(1);    
}

Is there any purpose/consequence of using it compared to the more common

int main(){    
  class foo{
    public:
      int x;
      foo(int y){x=y;}
  };

  foo * bar = new foo(1);    
}
xvan
  • 4,554
  • 1
  • 22
  • 37

1 Answers1

3

This is probably a matter of opinion but I think the first method is poor coding practice.

  1. It does not impact run time behavior.
  2. It makes the code harder to read.
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Do you believe that putting class definitions inside functions is ever good coding practice? _(honest question)_ –  Aug 07 '18 at 18:32
  • 2
    @gooroo7, I don't recall using it at my work over the last 20+ years. I can't tell whether others have a legitimate use for it. My assessement is that with the advent of `lambda` expressions, local classes/structs are probably not needed. You can get by with `std::pair` and `std::tuple` for most `struct`-like needs in a function. – R Sahu Aug 07 '18 at 18:36
  • @gooroo7 For context, the original code had multiple "maker" functions, each returning a pointer to a different implementation of a virtual class. – xvan Aug 07 '18 at 18:43
  • https://stackoverflow.com/questions/10072208/when-do-i-need-anonymous-class-in-c As @RSahu described, there is really no reason for anonymous classes using modern C++, but you may need a construct like that when also using existing C code. – Ben Jones Aug 07 '18 at 19:31
  • 2
    In the past, I used local classes to profit from RAII, e. g. as cleanup guards with tasks specific to the function. Today, though, I'd have a generic template guard accepting a lambda in constructor and executing it in destructor... – Aconcagua Aug 07 '18 at 20:01