typeid for blase class pointer

R

Ravi

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

class Vehichle {
public:
int i1;
};

class Car: public Vehichle {
public:
int i2;
};

int main()
{
Car c;
Vehichle *v = &c;
cout << typeid(*v).name() << endl; // <--- should output car
cout << typeid(c).name() << endl;
cout << (typeid(*v) == typeid(c)) << endl; // <--- should output
1
return 0;
}


code also at http://pastebin.com/f6928ebd1

I am learning C++. In the above code I am getting the the putput
Vehichle and 0 for the respective arrows. The book says different. Can
you please explain why?
 
V

Victor Bazarov

Ravi said:
using namespace std;
#include <iostream>
#include <typeinfo>

class Vehichle {
public:
int i1;
};

class Car: public Vehichle {
public:
int i2;
};

int main()
{
Car c;
Vehichle *v = &c;
cout << typeid(*v).name() << endl; // <--- should output car
cout << typeid(c).name() << endl;
cout << (typeid(*v) == typeid(c)) << endl; // <--- should output
1
return 0;
}


code also at http://pastebin.com/f6928ebd1

I am learning C++. In the above code I am getting the the putput
Vehichle and 0 for the respective arrows. The book says different. Can
you please explain why?

Probably because it's a crappy book.

V
 
J

James Kanze

Probably because it's a crappy book.

Or he's miscopied something. (Or both.)

(To the OP: you need at least one virtual function for typeid to
take the dynamic type into account. And to the writers of your
compiler: wouldn't a warning be appropriate here?)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,247
Latest member
crypto tax software1

Latest Threads

Top