1

how do you add a destructor to an anonymous class in C++? like in PHP if i want to run something when my class go out of scope it'd be

$foo = new class() {
        public $i=0;
        public function __destruct()
        {
            echo "foo is going out of scope!\n";
        }
    };

but in C++ with normal non-anonymous classes you specify the destructor with ~ClassName(){}, but anonymous classes doesn't have a name! so how do you add a destructor to

class {public: int i=0; } foo;

in c++? i tried using the variable name as the class name, but that didn't work:

class {
public:
  int i;
  ~foo(){std::cout << "foo is going out of scope!" << std::endl;}
} foo;

resulting in

prog.cc: In function 'int main()':
prog.cc:51:31: error: expected class-name before '(' token
   51 |     class {public: int i=0; ~foo(){std::cout << "foo is going out of scope!" << std::endl;};} foo;
      |                               ^

i also tried specifying just ~ but that didn't work either,

class {
public:
  int i=0;
  ~(){std::cout << "foo is going out of scope" << std::endl;}
} foo;

resulted in

prog.cc:48:30: error: expected class-name before '(' token
   48 |     class {public: int i=0; ~(){std::cout << "foo is going out of scope" << std::endl;};} foo;
      |                              ^
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
hanshenrik
  • 19,904
  • 4
  • 43
  • 89

1 Answers1

2

This cannot be done in C++. However, the real C++ analogue of anonymous classes is called an anonymous namespace:

namespace {
   struct foo {
     // ... whatever
     ~foo();
   };
}

// ... later in the same C++ source.

foo bar;

Now you can use and reference foos everywhere in this specific C++ source file. Other C++ source files may have their own anonymous namespace, with their own foos, without creating a conflict. The end result is pretty much the same thing as C-style anonymous structs (a.k.a. classes), except that they're not really anonymous, only their namespace is.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • i thought that was just how to access the global namespace :o – hanshenrik Feb 09 '22 at 12:11
  • @hanshenrik [Unnamed namespaces](https://en.cppreference.com/w/cpp/language/namespace#Unnamed_namespaces) – heap underrun Feb 09 '22 at 12:19
  • 1
    You need not place one-time-use classes in a namespace. You can have function-local classes, too. They still have to have a name to define a destructor, and you must implement all functions inline. – j6t Feb 09 '22 at 12:28