Search code examples
c++functionoopinheritancepure-virtual

Creating a new function in a derived class with same name but different return type


//Base.h
Class Base {
    //...
public:
    virtual std::ostream& display(std::ostream& os) const =0;
}

//Derived1.h
Class Derived1 : Base {
    //...
public:
    std::ostream& display(std::ostream&) const;//defined in Derived1.cpp
}
//Derived2.h
Class Derived2 : Derived1{
    //...
public:
    void display(std::ostream&) const;//error here!!!!!!!!!!!!!!!!!!!!
}

I must use void display(std::ostream&) const; because it is in the instructions for my lab and cannot change it. I have to call the display function from Derived1 in the display function from derived2, which is simple and i understand that. So like this

void Derived2::display(std::ostream& os) const{
    Derived1::display(os);
}

It will be called in main like this

Derived2 A;
A.display(std::cout);

The error in Derived2 is "return type is not identical to nor covariant with return type "std::ostream &" of overriden virtual function"

From what I read it's because the signature of the function(return type in this case) must match with the function it is override, but i think my lab wants me to create a new function not override it, but with the same name? Because i will have to call the display() from Derived1 in display() from Derived2. Any thoughts?

Oh yes and what i'm trying to do with display() is considered overloading, not overriding right?


Solution

  • You cannot do that, since return type is not covariant!

    I think you missed what the "lab" requests. Read these too:

    1. Override a member function with different return type
    2. C++ virtual function return type

    Welcome to StackOverflow by the way...Make sure for your future questions to construct a minimal example, for others to reproduce your issue, help them, to help you! Here is an example of a minimal example in this case:

    #include <iostream>
    
    class Base {
    public:
        virtual std::ostream& display(std::ostream& os) const =0;
    };
    
    class Derived1 : Base {
    public:
        std::ostream& display(std::ostream&) const
        {
            std::cout << "in Derived1.display" << std::endl;
        }
    };
    
    class Derived2 : Derived1 {
    public:
        void display(std::ostream&) const
        {
            std::cout << "in Derived2.display" << std::endl;
        }
    };
    
    int main()
    {
        Derived2 A;
        A.display(std::cout);
        return 0;
    }
    

    which would yield this error:

    main.cpp:18:10: error: virtual function 'display' has a different return type
          ('void') than the function it overrides (which has return type
          'std::ostream &' (aka 'basic_ostream<char> &'))
        void display(std::ostream&) const
        ~~~~ ^
    main.cpp:10:19: note: overridden virtual function is here
        std::ostream& display(std::ostream&) const
        ~~~~~~~~~~~~~ ^