3

I have a class named Student and I am creating a instance Alex in main program. While creating instance Alex, is it possible to print "Alex is being created". If the variable name is "Joe", it should print "Joe is being created".

This is my class defintion

class Student
{
    public:
    int rollNo;
    string address;

    Student(int rollNo, string address)
    {
        this.rollNo = rollNo;
        this.address = address;
    }
    //setter , getter functions.
};

// in main program

Student Alex;
Student Joe;

Note1: Yes, we can have variable "name" in Student class and pass name Alex/Joe while instantiating it and print as required inside constructor. But that is not my case. I purely don't want to pass name

Pendyala
  • 585
  • 1
  • 6
  • 17
  • You can use macros. Someone answered your question here: https://stackoverflow.com/questions/6622962/generic-way-to-print-out-variable-name-in-c – DutchJelly Jul 11 '19 at 10:47

3 Answers3

5

There is no way to automatically do this without macros, as C++ does not support reflection. One possibility is to use a macro on your call site:

#define CREATE_VARIABLE(type, name) \
    ::std::cout << "Creating " #name " of type " #type << '\n'; \
    type name

Use as:

CREATE_VARIABLE(Student, Alex);
CREATE_VARIABLE(Student, Joe){joeRollNo, joeAddress};
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
0

No, because the variable name is part of the expression which refers to your object in the scope where it is declared.

It isn't available to the object itself, might not even exist at runtime, and anyway it is trivial in C++ to create anonymous objects which aren't referred to by any named expression, or objects referred to by multiple different named expressions.

You can, of course, do this explicitly, or with a macro as Vittorio shows.

Useless
  • 64,155
  • 6
  • 88
  • 132
0

You can't print the name of the variable on creation. And it really wouldn't be helful. Consider of this code:

Student Alex;
Student Joe;
Student &some_student = Alex;
Student *another_student = &Alex;
Student Alex;
void print_students_address(const Student &student);

What name should be printed in each of those lines? Wouldn't you want to print the students name with the address instead of the name of the variable: "student"?

The proper solution would be to add a member "string name" to the Student class.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42