This example is from C++ in easy steps 5th ed (Mike McGrath) - Ch 8 Polymorphism, "Pointing to Classes".
I was wondering if anyone ran into this before or know why this fails to compile. I followed the example from the book and for some reason my program fails to compile and throws an exception related to casting. I even tried this on an online cpp compiler and got the same compiler exception so this rules out my compiler. I'm using the g++ compiler on Ubuntu. Please see attached screenshot. If anyone can assist that would be greatly appreciated! [Pointing to classes screenshot]
#include <iostream>
using namespace std;
class Base
{
public:
void Identify(int adr) const
{
cout << "Base class called by 0x" << hex << adr << endl;
}
};
class SubA : public Base { };
class SubB : public Base { };
int main()
{
// create 2 base class pointers each binding to a specific derived class
Base* ptrA = new SubA; //or ... SubA a; Base* ptrA = &a;
Base* ptrB = new SubB; //or ... SubB b; Base* ptrB = &b;
// use the pointers to call the base class method, passing the memory address of each for output
ptrA -> Identify((int) &ptrA);
ptrB -> Identify((int) &ptrB);
return 0;
}
Here's the compiler exception being thrown:
g++ classptr.cpp -o classptr classptr.cpp: In function ‘int main()’: classptr.cpp:29:26: error: cast from ‘Base**’ to ‘int’ loses precision [-fpermissive] ptrA -> Identify((int) &ptrA);
classptr.cpp:30:26: error: cast from ‘Base**’ to ‘int’ loses precision [-fpermissive] ptrB -> Identify((int) &ptrB);