I feel compelled to point out that a reference of type T is logically equivalent to a T * const. So technically, you can't get around using pointers.
To answer your question, it is absolutely possible to store a derived class in a reference to a base class. The issue is that A, B, and C all have potentially difference sizes. Here is one solution:
#include <stdio.h>
class A
{
public:
virtual void Function()
{
printf("A\n");
}
};
class B : public A
{
public:
virtual void Function()
{
printf("B: %d\n", var1);
}
int var1;
};
class C : public A
{
public:
virtual void Function()
{
printf("C: %d, %d\n", var1, var2);
}
int var1, var2;
};
class Factory
{
public:
A & Create(int a)
{
B &b = *new B;
b.var1 = a;
return b;
}
A & Create(int a, int b)
{
C &c = *new C;
c.var1 = a;
c.var2 = b;
return c;
}
};
Called like:
Factory factory;
A &a1 = factory.Create(0);
A &a2 = factory.Create(1, 2);
a1.Function();
a2.Function();
Which will print: B: 0 C: 1, 2
Unfortunately, it's not possible to allocate an A and then assign a B or C to it later, since their sizes don't match. You either must use a reference/pointer with dynamic allocation, or know the type ahead of time.