tags:

views:

156

answers:

4

Is it possible to get the object name too?

#include<cstdio>

class one {
public:
    int no_of_students;
    one() { no_of_students = 0; }
    void new_admission() { no_of_students++; }
};

int main() {
    one A;
    for(int i = 0; i < 99; i++) {
        A.new_admission();
    }
    cout<<"class"<<[classname]<<" "<<[objectname]<<"has "
        <<A.no_of_students<<" students";
}

where I can fetch the names, something like

[classname] = A.classname() = one
[objectname] = A.objectname() = A

Does C++ provide any mechanism to achieve this?

+1  A: 

You could try using "typeid".

This doesn't work for "object" name but YOU know the object name so you'll just have to store it somewhere. The Compiler doesn't care what you namned an object.

Its worth bearing in mind, though, that the output of typeid is a compiler specific thing so even if it produces what you are after on the current platform it may not on another. This may or may not be a problem for you.

The other solution is to create some kind of template wrapper that you store the class name in. Then you need to use partial specialisation to get it to return the correct class name for you. This has the advantage of working compile time but is significantly more complex.

Edit: Being more explicit

template< typename Type > class ClassName
{
public:
    static std::string name()
    {
        return "Unknown";
    }
};

Then for each class somethign liek the following:

template<> class ClassName<MyClass>
{
public:
    static std::string name()
    {
        return "MyClass";
    }
};

Which could even be macro'd as follows:

#define DefineClassName( className ) \
\
template<> class ClassName<className> \
{ \
public: \
    static std::string name() \
    { \
        return #className; \
    } \
}; \

Allowing you to, simply, do

DefineClassName( MyClass );

Finally to Get the class name you'd do the following:

ClassName< MyClass >::name();

Edit2: Elaborating further you'd then need to put this "DefineClassName" macro in each class you make and define a "classname" function that would call the static template function.

Edit3: And thinking about it ... Its obviously bad posting first thing in the morning as you may as well just define a member function "classname()" as follows:

std::string classname()
{
     return "MyClass";
}

which can be macro'd as follows:

DefineClassName( className ) \
std::string classname()  \
{ \
     return #className; \
}

Then you can simply just drop

DefineClassName( MyClass );

into the class as you define it ...

Goz
i would recommend not to allow default class name as it defeat the purpose. if we want class to be named, then enforce it on every class.
YeenFei
Yeah fair enough. Some people may prefer it to work with any class even other classes.
Goz
@Goz I guess you meant #className instead of ##className ?
usta
Aye ... sorry .... I didn't have a machine i could test compile that on at the time.
Goz
+5  A: 

use typeid(class).name

// illustratory code assuming all includes/namespaces etc

#include <iostream>
#include <typeinfo>
using namespace std;

struct A{};
int main(){
   cout << typeid(A).name();
}

It is important to remember that this gives an implementation defined names.

As far as I know, there is no way to get the name of the object at run time reliably e.g. 'A' in your code.

EDIT 2:

#include <typeinfo>
#include <iostream>
#include <map>
using namespace std; 

struct A{
};
struct B{
};

map<const type_info*, string> m;

int main(){
    m[&typeid(A)] = "A";         // Registration here
    m[&typeid(B)] = "B";         // Registration here

    A a;
    cout << m[&typeid(a)];
}
Chubsdad
@chubsdad: What is the output that you expect? I get `1A`, but the class name is `one`.
Lazer
@Lazer: As pointed out, this prints an implementation defined string. Refer my edit if you want a more fancy way
Chubsdad
+3  A: 

Do you want [classname] to be 'one' and [objectname] to be 'A'?

If so, this is not possible. These names are only abstractions for the programmer, and aren't actually used in the binary code that is generated. You could give the class a static variable classname, which you set to 'one' and a normal variable objectname which you would assign either directly, through a method or the constructor. You can then query these methods for the class and object names.

Alexander Rafferty
@Alexander: yes.
Lazer
@Lazer: May I know why?
Chubsdad
@chubsdad: Have a look at the code example in the question.
Lazer
@Lazer: the example provides absolutely no reason to want to retrieve the name `one`. That's what I'm asking about on the question discussion. Wanting the name of a C++ class is associated with ugly dynamic type hacks, and debugging. Wanting the name of a class in school which the program represents is not a job for runtime type information.
Potatoswatter
@Potatoswatter: It has nothing to do with classes in particular as you suggest. For example, if I have a variable `int a;`, is there a construct in C++ that allows me to do something similar to `if(a.type() == int) {}`. That is what I wanted to know.
Lazer
@Lazer: Yes, for that operation, use `if ( typeid(a) == typeid(int) )`; no need to mess around with strings. However, there properly isn't a need for that operation in the first place, since the static types are already known. If the static types are known by the compiler but flexible, as in templates, you should use `<type_traits>` template operations such as `is_same< type_of_a, int >` instead of runtime comparison. `typeid` only serves a practical purpose on classes with virtual methods, or for debugging templates.
Potatoswatter
+4  A: 

You can display the name of a variable by using the preprocessor. For instance

#include <iostream>
#define quote(x) #x
class one {};
int main(){
    one A;
    std::cout<<typeid(A).name()<<"\t"<< quote(A) <<"\n";
    return 0;
}

outputs

3one    A

on my machine. The # changes a token into a string, after preprocessing the line is

std::cout<<typeid(A).name()<<"\t"<< "A" <<"\n";

Of course if you do something like

void foo(one B){
    std::cout<<typeid(B).name()<<"\t"<< quote(B) <<"\n";
}
int main(){
    one A;
    foo(A);
    return 0;
}

you will get

3one B

as the compiler doesn't keep track of all of the variable's names.

As it happens in gcc the result of typeid().name() is the mangled class name, to get the demangled version use

#include <iostream>
#include <cxxabi.h>
#define quote(x) #x
template <typename foo,typename bar> class one{ };
int main(){
    one<int,one<double, int> > A;
    int status;
    char * demangled = abi::__cxa_demangle(typeid(A).name(),0,0,&status);
    std::cout<<demangled<<"\t"<< quote(A) <<"\n";
    free(demangled);
    return 0;
}

which gives me

one<int, one<double, int> > A

Other compilers may use different naming schemes.

Scott Wales
@Scott: Why do we get `3one`? What is `3`?
Lazer
@Lazer No idea, as people say the result of `typeid` is platform specific. It's probably something to do with C++'s name mangling scheme.
Scott Wales
If I try `template <typename T> class one{};` and use a `one<int>` I get `3oneIiE` as the class name, so it is indeed to do with name mangling (The stuff probably means class with a `3` character name `one` with `I` one template argument `i` (int) `E` end of arguments)
Scott Wales
+1 I was not aware that we even have such functionality in C++
hype