Home > other >  Instantiate object and pass its name to constructor using c macro
Instantiate object and pass its name to constructor using c macro

Time:11-28

lets say

Class A{
   A(string name){
       ....
   }
}

So when the object is created:

A objectNumber324 = new A("objectNumber324");
A objectNumber325 = new A("objectNumber325");

In my case as the object names are pretty long, I am looking for macro to simplify that code to:

CreateA(objectNumber325)

There is some discussion how to pass variable name to a function here. But that is not quite the same thing, as I want to create the object and pass its name to constructor.

CodePudding user response:

#include <string>
#include <iostream>

#define CreateA(name) \
        A* name = new A(#name)

// With type
#define CREATE_WITH_TYPE(type, name) \
        type* name = new type(#name)

// With name decoration
#define CREATE_WITH_DECO(type, name) \
        type* my_##name = new type(#name)

class A {
public:
   A(std::string name){
       std::cout << name << " created.\n";
   }
};

int main() {
    // example
    CreateA(objectNumber325);
    CREATE_WITH_TYPE(A, objectNumber324);
    CREATE_WITH_DECO(std::string, a_string);
    delete objectNumber324;
    delete objectNumber325;
    delete my_a_string;
}
  • Related