Omer
Omer

Reputation: 57

C++ Trying to add >> Operator Overload To Template

I have a class IPrintable which is a template and a class which derives from it - Date. I want to add the operator >> to the template but keep getting an error:

source.cpp(16): error C2259: 'Date': cannot instantiate abstract class
source.cpp(16): note: due to following members:
source.cpp(16): note: 'void IPrintable<Date>::toIs(std::istream &)': is abstract
iprintable.h(19): note: see declaration of 'IPrintable<Date>::toIs'

I have successfully added the << operator to the template this way:

virtual void toOs(ostream& os) const = 0;
friend ostream& operator << (ostream& output, const IPrintable& toPrint) {
    toPrint.toOs(output);
    return output;
}

And then I have declared virtual void toOs(ostream& os) const = 0; to date.h and implemented it in date.cpp.

This is my IPrintable.h:

#pragma once
#include <iostream>
#include <string>
using namespace std;

template <class T>
class IPrintable {
private:


public:

    virtual void toOs(ostream& os) const = 0;
    friend ostream& operator << (ostream& output, const IPrintable& toPrint) {
        toPrint.toOs(output);
        return output;
    }

    virtual void toIs(istream& input) = 0;
    friend istream& operator >> (istream& input, IPrintable& toSet) {
        toSet.toIs(input);
        return input;
    }

};

This is the declaration of in Date.h, under public:

virtual void toOs(ostream& output) const;
virtual void toIS(istream& input);

This is the implementation of the << (toOs) and >> (toIs) in Date.cpp:

void Date::toOs(ostream& output) const {
    if (!isLeapYear(this->getDay(), this->getMonth(), this->getYear())) {
        cout << "Not a leap year";
        return;
    }
    output << getDay() << "/" << getMonth() << "/" << getYear();
}

void Date::toIS(istream& input) {
    int index;
    string str;
    input >> str;
    index = str.find('/');
    this->setDay(stoi(str.substr(0, index)));
    str = str.substr(index + 1);
    index = str.find('/');
    this->setMonth(stoi(str.substr(0, index)));
    str = str.substr(index + 1);
    this->setYear(stoi(str));
}

Please, if any more information is needed please let me know and I will do my best to provide it.

Thanks!

Upvotes: 0

Views: 52

Answers (1)

Mark
Mark

Reputation: 1056

Your Date::toIS has a capital S, while your IPrintable::toIs does not. If you add override to the declaration of Date::toIS, you would see that it doesn't actually override anything.

Upvotes: 2

Related Questions