Difficulty with Abstract class

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;

}
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 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?
Last edited on
napada99 wrote:
I'm getting a garbage value for Month m

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?

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
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <limits>

enum Month {
    JAN = 1,
    FEB,
    MAR
};

class Show {
public:
    virtual void 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.
Topic archived. No new replies allowed.