Tu Gjac Chjem Bao
Tu Gjac Chjem Bao

Reputation: 23

Cast a base class issues

class YourInterface {
public:
    YourInterface(){
    }

    virtual ~YourInterface(){
    }

    virtual void saveData(Data data) = 0; //Pure virtual = Childs are forced to implement those functions to become non abstract
    virtual Data loadData() = 0;
};

//One implementation to load and save data to/from a xml file
class XmlImplementation : public YourInterface {
public:
    XmlImplementation(){
    }

    virtual ~XmlImplementation(){
    }

    //Overriding functions:
    void saveData(Data data){
        //Save data to a xml file here
    }

    Data loadData(){
        //Load data from a xml file here
    }
};

void main(){
    YourInterface* p;
    p = (YourInterface*) new XmlImplementation();

    p->loadData(); //We just want to get our Data here, we dont care whether its from a xml or binary file etc.
}

Please take that as an example, I know it is not good but I can't write any better than that.

I'd like to know better why the cast in main refuses to work properly ? and it has been suggested as an errorful cast.

Upvotes: 0

Views: 114

Answers (2)

johnsyweb
johnsyweb

Reputation: 141770

There's no need for the (C-style or otherwise) cast here. Your main() function (which should always return int) should look like this:

int main()
{
    YourInterface* p = new XmlImplementation();

    p->loadData();
}

If you're getting an error, it's not because of the cast.

N.B: In C++, it's customary to use static_cast when typecasting from a pointer to a derived class to a pointer to a base class.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

Nothing wrong with the code, except that the cast is actually unnecessary. The code would compile and work fine without it.

Upvotes: 3

Related Questions