In my program given below:
#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;
I'm getting the correct value for Month m 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 ?
Why are you casting a Date pointer to a Month pointer? If you want to be able to access the month from outside the class you should add an accessor function?
What do you presume you should obtain?
A “Month” is an enum, i.e. an integer value. Do you think a reinterpret_cast<> could be able to turn a complex object, composed of three variables and several function, into an integer?
#include <iostream>
#include <limits>
enum Month {
JAN = 1,
FEB,
MAR
};
class Show {
public:
virtualvoid display() = 0;
};
class Date : public Show {
private:
Month m {JAN};
int day {0};
int year {0};
public:
Date(Month mName, int dayName, int yearName)
: m {mName}, day {dayName}, year {yearName}
{}
void display() override { std::cout << m << '\n'; }
Month getMonth() const { return m; }
};
void displayData(void *data[]);
void waitForEnter();
int main(int argc, char**argv)
{
Date d1(JAN, 28, 2017);
void* data[1];
data[0] = &d1;
displayData(data);
waitForEnter();
return 0;
}
void displayData(void *data[])
{
Date* mydate = static_cast<Date*>(data[0]);
Month m = mydate->getMonth();
std::cout << m << '\n';
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
You could also consider using templates instead of void pointers.