Reputation: 1
#include <iostream>
#include <ostream>
using namespace std;
enum Month
{
jan = 1,
feb,
mar
};
class Show
{
public:
virtual void Display() = 0;
};
class Date : public Show
{
private:
Month m;
int day;
int year;
public:
Date( Month mName, int dayName, int yearName )
{
m = mName;
day = dayName;
year = yearName;
}
void Display()
{
cout << this->m << endl;
}
};
void displayData( void *data[] )
{
Month m = *( reinterpret_cast<const Month*> ( data[ 0 ] ) );
cout << m << endl;
}
int main( int argc, char**argv )
{
Date d1( jan, 28, 2017 );
void * data[ 1 ];
data[ 0 ] = &d1;
displayData( data );
return 0;
}
I'm getting the correct value for Month m in the function void displayData but when I inherit the Date class from the abstract class Show, then I'm getting a garbage value for Month m. Can anyone tell me why is this happening ?
Upvotes: 0
Views: 77
Reputation: 789
You should not use the void pointer. Use a base class like Show instead, like:
void displayData( Show *data[] )
{
data[0]->Display();
}
int main( int argc, char**argv )
{
Date d1( jan, 28, 2017 );
Show* data[ 1 ];
data[ 0 ] = &d1;
displayData( data );
return 0;
}
Else how you would devide the void pointers to their classes?
Upvotes: 0
Reputation: 61969
You are reinterpret-casting a Date
as a Month
. So, you are assuming that this is a safe conversion, but it isn't. It happens to work purely by accident when the Date
class is just plain data, but when you derive the Date
class from Show
then the structure of the class becomes more complicated, and the accident does not hold true anymore.
What is probably happening is that the first element in Date
is now a pointer to the virtual method table of the class rather than the first member declared in the class.
Upvotes: 2