vtable on stack

Axel Freyn axel-freyn@gmx.de
Tue Feb 2 12:41:00 GMT 2010

Hi Frank,
On Tue, Feb 02, 2010 at 04:06:56AM -0800, John (Eljay) Love-Jensen wrote:
> Hi Frank,
> > Do virtual functions work with class objects created on the stack?
> Yes.
> > Consider the example below.
> I think you may be misunderstanding this line:
>    A y = B();
> That makes an A on the stack, since y is an A.  y does not become a B
> from the assignment.  Rather B is sliced to an A.
> So that A y = B(); is not analogous to:
>    A* x = new B();
> To fix your example, do this:
>    B y = B();

Another possibility would be to use references and write:
  const A &y = B();
(the "const" is necessary, as you can't create a non-const reference to
a temporary object (that's a limitation I really don't like - sometimes
it would be nice to have:-)). Of course, the drawback is that y is
constant, so you have to define the member functions as:
 virtual void f() const { cout << "Class A" << endl; }
 void f() const { cout << "Class B" << endl; }

Then, y.f() outputs "Class B".

A third way is to use an additional variable, where you store the
B-object (so it's no temporary, and you can create a non-constant
reference to it), and then create a reference of type A to it:
B y1 = B();
A & y = y1;

Then, y refers to an object of type B and "y.f()" outputs "Class B".

I think, it depends on your situation what is the "best" solution.


More information about the Gcc-help mailing list