Home > database >  Inheritance and operator overloading
Inheritance and operator overloading

Time:07-12

Hi I am new to c and had some conceptual questions that I wasn't able to find any direct answers to online. So if we have a parent class and multiple children classes and we want to create an overloaded input function for it. So do we create it for every child class or just for once for the parent class. Also do we have to define the function in every class even if we leave it blank? For example:

class A{
public:
   friend std::istream &operator >> (std::istream &, A &);
   friend std::ostream &operator << (std::ostream &, const A &);
}

class B: public A{

}

class C: public A{

}

So would the above be correct and using this implementation I can take input of both B and C?

What would be the correct method if I had to implement another operator like that has different implementations for class B and C. Do I just define them individually (because I read that friend functions cannot be inherited, i might be wrong)

CodePudding user response:

So, what @john said, basically, something like this (reduced to a minimal example):

#include <iostream>

class A {
public:
    friend std::ostream &operator << (std::ostream &os, const A &a);

private:
    virtual std::ostream& print (std::ostream &os) const { std::cout << m_x; return os; }
    int m_x = 42;
};

class B: public A {
    std::ostream& print (std::ostream &os) const override { std::cout << m_y; return os; }
    int m_y = 84;
};

std::ostream &operator << (std::ostream &os, const A &a) { return a.print (os); }

int main ()
{
    B b;
    std::cout << b;
}

Note that you don't have to override print in any particular derived class if you don't want to. It's just a virtual function like any other.

  • Related