Calling base class functions and temp results

Started by
3 comments, last by maxest 14 years, 10 months ago
I actually didn't know how to call that thread... Take a look at that code:

class Base
{
public:
	int a, b, c;

public:
	friend istream & operator >> (istream &_istream, Base &base);
};

istream & operator >> (istream &_istream, Base &base)
{
	_istream >> base.a;
	_istream >> base.b;
	_istream >> base.c;

	return _istream;
}



class Derivative: public Base
{
public:
	int d;

public:
	friend istream & operator >> (istream &_istream, Derivative &derivative);
};

istream & operator >> (istream &_istream, Derivative &derivative)
{
	_istream >> (Base)derivative; // something's wrong
	_istream >> derivative.d;

	return _istream;
}
I just want to make a "shortcut" and assign a, b and c with the function called in line of interest (the one with comment "some's wrong"). However, it just doesn't work. I could do something like:

istream & operator >> (istream &_istream, Derivative &derivative)
{
	_istream >> derivative.a;
	_istream >> derivative.b;
	_istream >> derivative.c;
	_istream >> derivative.d;

	return _istream;
}
But this is only a code duplication which I want to avoid.
Advertisement
It seems like you want:
	_istream >> (Base &)derivative;
Yes, it worked of course :)
I suppose it's that I need to cast on the *reference* (Base&), and casting only on (Base) gives *value*..? Could someone explain it in more details, please?
(Base) derivative copy constructs a temporary Base object from the derivative object. A temporary can't be bound to a non-const reference.
So it's more or less what I thought about. Thanks for clarifying this to me!

This topic is closed to new replies.

Advertisement