In relation to question "reference to abstract class" I wrote the following example:
#include <iostream>
#include <vector>
class data
{
public:
virtual int get_value() = 0;
};
class data_impl : public data
{
public:
data_impl( int value_ ) : value( value_ ) {}
virtual int get_value() { return value; }
private:
int value;
};
class database
{
public:
data& get( int index ) { return *v[index]; }
void add( data* d ) { v.push_back( d ); }
private:
std::vector< data* > v;
};
int main()
{
data_impl d1( 3 );
data_impl d2( 7 );
database db;
db.add( &d1 );
db.add( &d2 );
data& d = db.get( 0 );
std::cout << d.get_value() << std::endl;
d = db.get( 1 );
std::cout << d.get_value() << std::endl;
data& d_ = db.get( 1 );
std::cout << d_.get_value() << std::endl;
d_ = db.get( 0 );
std::cout << d_.get_value() << std::endl;
return 0;
}
To my surprise, the example prints:
3
3
7
7
and it looks like the reference assignment does the work differently from my expectation. I would expect:
3
7
7
3
Could you please point what my mistake is?
Thank you!
In
data& d = db.get( 0 );
std::cout << d.get_value() << std::endl;
d = db.get( 1 );
std::cout << d.get_value() << std::endl;
the first statement is a reference initialization, while the third statement is a slicing assignment.
You can not re-seat a reference.
Cheers & hth.,
The reason is, references can't be reassigned.
You assigned the reference d to the first element in db:
data& d = db.get( 0 );
Then later you tried to reassign it:
d = db.get( 1 );
However, this doesn't change the reference itself, instead it changes the value the reference points to.
However, in this case the reference is to an abstract base class which contains no data. So the assignment isn't changing anything.
In effect you print the first element in db twice, then the 2nd element again twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With