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;
}
With your code, I would’t recommend it, because
Containeris the owner ofbaseand a reference, semantically, means something else (an alias).Technically, there’s nothing stopping you:
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:
instead of
if you used pointers. Of course, using a
std::unique_ptrinstead of either of these two would make life a whole lot easier.Also, be sure to implement (or declare as
privateordeleted) the copy constructor or assignment operator.Later spot – You need to provide
Basewith avirtualdestructor, otherwise you’ll run into undefined behavior territory when you’ll attempt to clean up the memory.