0

What is the best way to get a 'shared_ptr' class name?

Lets say I have:

std::shared_ptr<Object> objPtr;

How can I get "Object" as a string?

guygrinberger
  • 327
  • 2
  • 14
  • How do you want to get the type pointed to? What is the use case for it? – NathanOliver Jun 11 '18 at 12:51
  • 5
    `std::string name = "Object";`? A little more serious, what is the actual problem you have? Why do you need the string? What for? Please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). I also recommend [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/) and that you read all of http://idownvotedbecau.se/. – Some programmer dude Jun 11 '18 at 12:52
  • 1
    Let Object inherit from a class who has a variable and setter/getter for the name. – user743414 Jun 11 '18 at 12:52
  • Perhaps you should consider using Runtime Polymorphism if you need to define specific behaviors for your derived objects. Or maybe the `visit` method of `std::variant` may work for you. C++ isn't designed to support type introspection; so you may be better off with another approach to your problem. – Matthew Nakayama Jun 12 '18 at 05:43

2 Answers2

3

You can do it this way:

typeid(decltype(*objPtr)).name()

Note however that the name it returns may be "mangled." How this is done, and how to "demangle" the name, is platform-dependant (aka "implementation defined").

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 3
    ...and to get a demangled and "nice" output, see [this answer](https://stackoverflow.com/a/4541470/1753435) (non-portable, though). – andreee Jun 11 '18 at 12:54
  • 1
    Problem is that what is returned by `typeid(...).name()` is implementation defined. – Peter Jun 11 '18 at 12:54
1

The name of the class, as a string, is generally not accessible at runtime. The easiest thing to do is simply define the class name as a const member field of the object, as one of the comments suggested.

However, I caution that it is very likely that program designs that require the string name of the class are a very bad idea, and encourage you to make better use of C++'s strongly-typed nature rather than checking if the name satifies certain conditions. Unless, of course, you simply want to name of the class for debug logging.

Qwertycrackers
  • 626
  • 4
  • 12
  • The fact I used 'shared_ptr's to point my objects made thing a little harder like knowing the base class for certain pointer – guygrinberger Jun 11 '18 at 14:43
  • If you have a superclass, but want to find out the base class, that's a sign that your class structure is badly designed. Move the interface you want to access from the base class up to the superclass. – Qwertycrackers Jun 11 '18 at 15:16