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!