Why is the operators << and >> called in base class if they are defined as 'friend' when calling << and >> in child class?
Code:
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Baza
{
protected:
int n;
public:
Baza() { cout << "B\n"; }
virtual ~Baza() { cout << "~B\n"; }
friend istream& operator>>(istream& in, Baza& b);
friend ostream& operator<<(ostream& out, const Baza& b);
};
istream& operator>>(istream& in, Baza& b)
{
cout<<"op >>"<<endl;
return in;
}
ostream& operator<<(ostream& out, const Baza& b)
{
cout<<"op<<"<<endl;
return out;
}
class Derivata : public Baza
{
public:
Derivata() { cout << "D\n"; }
~Derivata() { cout << "~D\n"; }
};
int main()
{
vector<Derivata> v;
v.push_back(new Derivata);
// works
Derivata d;
cin>>d;
cout<<d;
return 0;
}
Is c++ compiler creating a operators that calls the base class method's operator by default when compiling?
Rephrase: in base class (which is baza) are defined operators << and >> as friend. Derivata class inherits the 'baza' (base class), but operators are not inherited because they're friends. why are they called if i use >> and << in 'derivata' class?
void foo(const Baza&) {} int main() { Derivata d; foo(d); }
Would you expect this version to not work?friend ...
and ensurefriend
is not a subject of your question.