similar (not the same) operators overloading

gcc version 4.4.3 (Gentoo 4.4.3-r2 p1.2)

why when i am overloading similar operators (like operator+() and operator+(const T&) one in parent and other in derived classes i get compilation error

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
#include <cstdlib>
#include <iostream>

using namespace std;

class parent {
public:
        virtual parent operator+()const {
                wcout << "parent::+()" << endl;
                return *this;
        }
};

class derived: public parent {
public:
        virtual derived operator+(const derived&)const {
                wcout << "derived::+(derived)" << endl;
                return *this;
        }
};

int main(int argc, char** argv) {
        derived a, b, c;
        a = b+c;
        parent d;
        d = +c;
        return EXIT_SUCCESS;
}


main.cpp: In function 'int main(int, char**)':
main.cpp:26: error: no match for 'operator+' in '+c'
main.cpp:16: note: candidates are: virtual derived derived::operator+(const derived&) const

but if i redefine virtual operator in derived class everything is ok

in derived class:
1
2
3
4
        virtual parent operator+()const {
                wcout << "derived::+()" << endl;
                return *this;
        }
Polymorphism works only when you have base references (or pointers) to derived objects. For example, this would work:

1
2
3
4
5
6
7
8
9
10
11
int main(int argc, char** argv)
{
    derived a, b, c;
    a = b+c;

    parent d;
    parent & e=c;
    d = +e;
    
    return EXIT_SUCCESS;
}

EDIT: Though... Now that I look at it again, this is not a polymorphism issue... It reminds me a lot of that one:

http://cplusplus.com/forum/beginner/24978/ (main topic)
http://cplusplus.com/forum/beginner/24978/#msg132439 (my explanation)
Last edited on
Ok, thank you, i've understood this problem, but could you give some rules about it such as ANSI C++ or other standart?
Topic archived. No new replies allowed.