1

I'm curious if in the following program Base* base in class Container can be replaced with Base& base?
With Base base it can't be replaced, because Base is abstract.
With Base& base the object should be allocated somewhere, so I still would not be able to get rid of the pointer to the allocated object.

#include <iostream>
class Base
{   public:
    virtual void str()=0;
};

class A : public Base
{   int i;
    public:
    A(int i):i(i){}
    void str(){std::cout<<i<<std::endl;}
};

class B : public Base
{   double f;
    public:
    B(double f):f(f){}
    void str(){std::cout<<f<<std::endl;}
};

class Container
{   Base *base;
    public:
    Container(int i)   { base=new A(i);}
    Container(double f) { base=new B(f);}
    void str(){ base->str();}
};
int main ()
{   
    Container c1(8),c2(13.0);  
    c1.str();   
    c2.str();  
    return 0;  
}
Coding Mash
  • 3,338
  • 5
  • 24
  • 45
titus
  • 5,512
  • 7
  • 25
  • 39
  • I think this post should give you an answer : http://stackoverflow.com/questions/7192069/polymorphic-c-references – Tazadar Aug 30 '12 at 14:40

1 Answers1

4

With your code, I would't recommend it, because Container is the owner of base and a reference, semantically, means something else (an alias).

Technically, there's nothing stopping you:

class Container
{   Base &base;
    public:
    Container(int i) : base(*new A(i))   {}
    Container(double f) : base(*new B(f)) {}
    void str(){ base->str();}
};

Note that references have to be initialized in the initializer list.

You'd still need to clean up the memory, and it would look ugly with a reference:

~Container() { delete &base; }

instead of

~Container() { delete base; }

if you used pointers. Of course, using a std::unique_ptr instead of either of these two would make life a whole lot easier.

Also, be sure to implement (or declare as private or deleted) the copy constructor or assignment operator.

Later spot - You need to provide Base with a virtual destructor, otherwise you'll run into undefined behavior territory when you'll attempt to clean up the memory.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625