Base class -> Derived class and vice-versa conversions in C++

Posted by Ivan Nikolaev on Stack Overflow See other posts from Stack Overflow or by Ivan Nikolaev
Published on 2011-01-02T15:30:59Z Indexed on 2011/01/02 15:53 UTC
Read the original article Hit count: 460

Filed under:
|
|
|

Hi! I have the following example code:

#include <iostream>
#include <string>

using namespace std;

class Event
{
public:
    string type;
    string source;
};

class KeyEvent : public Event
{
public:
    string key;
    string modifier;
};

class MouseEvent : public Event
{
public:
    string button;
    int x;
    int y;
};

void handleEvent(KeyEvent e)
{
    if(e.key == "ENTER")
        cout << "Hello world! The Enter key was pressed ;)" << endl;
}

Event generateEvent()
{
    KeyEvent e;
    e.type = "KEYBOARD_EVENT";
    e.source = "Keyboard0";
    e.key = "SPACEBAR";
    e.modifier = "none";

    return e;
}

int main()
{
    KeyEvent e = generateEvent();

    return 0;
}

I can't compile it, G++ throws an error of kind:

main.cpp: In function 'int main()':
main.cpp:47:29: error: conversion from 'Event' to non-scalar type 'KeyEvent' requested

I know that the error is obvious for C++ guru's, but I can't understand why I can't do the conversion from base class object to derived one. Can someone suggest me the solution of the problem that I have? Thx in advice

© Stack Overflow or respective owner

Related posts about c++

Related posts about casting