typeid on vector

From the snippet of code below - is there anyway to return the actual name of the object?

Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  //
//  main.cpp
//  polymorphic vector example
//
//  Created by James Farrow on 16/02/2017.
//  Copyright © 2017 James Farrow. All rights reserved.
//

#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
#include "textClass.hpp"
#include "FancyText.hpp"
#include "FixedText.hpp"


int main(int argc, const char * argv[]) {
    
    std::vector<Text *> texts { new Text("Wow"), new FancyText("Wee", "[", "]", "-"), new FixedText,
                                new FancyText("Whoa", ":", ":", ":") };
    
    for (auto t : texts){
        std::cout << t->get() << '\n';
        std::cout << typeid(t).name() << '\n';
    }
    
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <vector>
#include <typeinfo>

struct Text
{
    std::string m_line;
    Text(const std::string& line) : m_line(line){}
    virtual ~Text(){}
};

struct FancyText : public Text
{
    using Text::Text;
    bool m_italics = false;
};

int main()
{
    std::vector<Text*> texts {new Text(std::string("Wow")), new FancyText (std::string("Wow, italics"))};

    for (auto& elem : texts)
    {
        if (dynamic_cast<FancyText*>(elem))
        {
            std::cout << "FancyText \n";
        }
        else if (dynamic_cast<Text*>(elem))
        {
            std::cout << "Text \n";
        }
        else
        {
            std::cout << "Unknown \n";
        }
    }
    for (auto& elem : texts)
    {
        delete elem;
    }
}

Thank you!! This is related to my other post lol - inheritance and polymorphism!

typeid is pointing to a base class right? that swhy it always returns the bse class id?
Thanks again.
typeid is pointing to a base class right? that swhy it always returns the bse class id?
... indeed because it's a vector of Text*'s
Thanks gunnerfunner - I really appreciate your input!

Cheers
> typeid is pointing to a base class right? that swhy it always returns the bse class id?

Yes. To get the dynamic type of the pointed-to object, de-reference the pointer:
for( auto ptr : texts ) if( ptr != nullptr ) std::cout << typeid(*ptr).name() << '\n' ;
Thanks everyone!
Topic archived. No new replies allowed.