reference instead of pointer to abstract class - c++

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 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.

Related

Is it legal to use the address of a member to initialize a base-class?

Is this code legal?:
class BaseClass
{
public:
BaseClass (int *p) : p_ (p) { }
private:
int *p_;
};
class SubClass : public BaseClass
{
public:
SubClass () : BaseClass (&i_), i_ (123) {}
private:
int i_;
};
It is well-known that the base-class gets constructed before the members of the sub-class, which is why I'm wondering.
Yes, this is fine: while the lifetime of (the relevant instance of) SubClass::i has yet to begin, its storage exists, and a pointer to it may be formed (though not used for much yet).

Heap allocation and Initialisation of a base class in the initializer list of its derived class’ constructor

class Base
{
int n;
public:
Base(int n)
: n(n)
{}
...
}
class Derived : Base
{
public:
Derived(int n)
: Base(n)
{}
}
void function()
{
Derived* obj = new Derived(10);
...
delete obj;
}
I have a similar situation as with the above code, where Derived is just a wrapper of Base. To access the object in function I’m using a Derived pointer on purpose. My understanding is that the whole object it’s allocated on the heap, including the Base part and that delete reclaims all the memory, even if I use a Derived pointer and Base is not polymorphic. Is this correct or there is something more to it ?
Thanks

returning derived class from overrided method, declared as returning base copy

This is a recurrent problem once again. Someone know a easy way to do that? Imagine I have the following:
class Base
{
public:
...
Base property(const std::string& name)=0;
};
class Derived:public Base
{
public:
Derived();
Derived(const Derived&& val);
Base property(const std::string& name)
{
Derived z;
return z;
}
}
There is a way for the Derived::property return being (internally) a Derived copy instead of only Base part copy, and with the Derived move constructor invoked?
May be a stupid question, but really I dont find solution. Why copy constructors on return dont copy the specialized class?
Thanks you!
You can't do this.
Returning by value conceptually (ignoring RVO and move semantics) means making a copy of whatever you return by using the copy constructor of the type which the function is declared to return. If you return a Derived, a copy of type Base will be made and you'll lose the Derived part of the object. This is known as slicing.
If you want to return a Derived object as a Base, you'll need to use pointers.
The only aproximation I can find for who search something similar (related with X3liF, TartanLlama and other responses)
#define overridable(T) ovr<T>
#define return_overload_allowed(TYPE) friend struct ovr<TYPE>; virtual void* clone() const
#define return_overload_basic_allowed(TYPE) friend struct ovr<TYPE>; virtual void* clone() const{return new TYPE(*this);}
template<typename T> struct ovr
{
T* _obj;
ovr(const T& t)
: _obj(reinterpret_cast<T*>(t.clone()))
{;}
ovr(ovr<T>&& v)
: _obj(v._obj)
{
v._obj=nullptr;
}
operator T&()
{
return *_obj;
}
virtual ~ovr()
{
delete _obj;
}
};
class BASE
{
return_overload_basic_allowed(BASE);
public:
virtual overridable(BASE) method1();
virtual ~BASE();
};
class DERIVED: public BASE
{
return_overload_basic_allowed(DERIVED);
public:
virtual overridable(BASE) method1()
{
DERIVED a;
return a;
}
virtual ~DERIVED();
};
DERIVED a;
auto x = a.method1();
BASE& really_derived = x;
This compiles fine. But don't meet practical and smart requiriments... :(

defer the initalization of boost::scoped_ptr

I have defined a member variable as follows. Since the variable will not be passed around, so I decide to use scoped_ptr rather than shared_ptr here.
class ClassName
{
public:
ClassName()
{
Initialize();
}
virtual void Initialize() = 0;
protected:
boost::scoped_ptr<int> m_scpInt;
}
class ClassNameB : public ClassName
{
public:
virtual void Initialize()
{
m_scpInt.reset(new int(100));
}
}
Due to the limit of the scoped_ptr, if I decide to defer the initialization of the variable in a later time, the only option I get is to call reset.
Q1> Is this a good practice?
Q2> Otherwise, is there a better solution?
Thank you
/// Updated -1 ///
This is what I really want to do.
I want to enforce that each of the derived class define a function called Initialize and which in turn calls function InitializeVarA and InitializeVarB. As you indicate, that we cannot call virtual function in the constructor.
class ClassName
{
public:
ClassName()
{
}
virtual void Initialize()
{
InitializeVarA();
InitializeVarB();
}
protected:
virtual void InitializeVarA() {}
virtual void InitializeVarB() {}
}
class ClassNameB : public ClassName
{
public:
ClassNameB()
{
}
virtual void Initialize()
{
InitializeVarA();
InitializeVarB();
}
protected:
virtual void InitializeVarA() {}
virtual void InitializeVarB() {}
}
ClassNameB cb;
cb.Initialize();
Do I have a better solution than this?
Is this a good practice?
Using reset to reset a scoped pointer is fine.
Trying to initialise a derived class by calling a virtual function from the base class's constructor is not just bad practice; it's wrong. At that point, the dynamic type of the object is the base class, and the function is pure virtual, so calling it gives undefined behaviour.
Even if you made it non-pure, you still can't call the derived class's override at that point, so the pointer won't be reset.
Otherwise, is there a better solution?
You could do it in the derived class's constructor, which is invoked immediately after the base class's:
class Base {
public:
Base() { /* don't call any virtual functions here */ }
protected:
boost::scoped_ptr<int> p;
};
class Derived : public Base {
public:
Derived() {
p.reset(new int(100));
}
};
Or you could pass the allocated memory to the base class constructor and initialise the pointer from that. That's slightly dangerous though - you must make sure you initialise the pointer immediately, before anything that might throw an exception, or the memory might leak.
class Base {
public:
Base(int * p) : p(p) {}
private: // doesn't need to be protected now
// (unless something else in the derived class needs access)
boost::scoped_ptr<int> p;
};
class Derived : public Base {
public:
Derived() : Base(new int(100)) {}
};
In C++11, you could use unique_ptr, which is movable, to avoid that risk of a leak:
class Base {
public:
typedef std::unique_ptr<int> ptr;
Base(ptr && p) : p(p) {}
private:
ptr p;
};
class Derived : public Base {
public:
Derived() : Base(ptr(new int(100))) {}
};

How can I get polymorphic behavior in a C++ constructor?

I have a base class that I want to look like this:
class B
{
// should look like: int I() { return someConst; }
virtual int I() = 0;
public B() { something(I()); }
}
The point being to force deriving classes to override I and force it to be called when each object is constructed. This gets used to do some bookkeeping and I need to know what type of object is being constructed (but I otherwise treat the current object as the base class).
This doesn't work because C++ won't let you call an abstract virtual function from the constructor.
Is there a way to get the same effect?
Based on this link it would seem that the answer is there is no way to get what I want. However what it says is:
The short answer is: no. A base class doesn't know anything about what class it's derived from—and it's a good thing, too. [...] That is, the object doesn't officially become an instance of Derived1 until the constructor Derived1::Derived1 begins.
However in my case I don't want to know what it is but what it will become. In fact, I don't even care what I get back as long as I the user can (after the fact) map it to a class. So I could even use something like a return pointer and get away with it.
(now back to reading that link)
You can't call virtual methods from the constructor (or to be more precise, you can call them, but you'll end up calling the member function from the class currently being constructed)., the problem is that the derived object does not yet exist at that moment. There is very little you can do about it, calling virtual methods from the constructor polymorphically is simply out of the question.
You should rethink your design -- passing the constant as an argument to the constructor, for example.
class B
{
public:
explicit B(int i)
{
something(i);
}
};
See C++ faq for more. If you really want to call virtual functions during construction, read this.
Perhaps use a static factory method on each derived type? This is the usual way to construct exotic objects (read: those with very specific initialisation requirements) in .NET, which I have come to appreciate.
class Base
{
protected Base(int i)
{
// do stuff with i
}
}
class Derived : public Base
{
private Derived(int i)
: Base(i)
{
}
public Derived Create()
{
return new Derived(someConstantForThisDerivedType);
}
}
Calling virtual methods in base constructors is generally frowned upon, as you can never be certain of a particular method's behaviour, and (as somebody else already pointed out) derived constructors will not have yet been called.
That will not work as the derived class does not yet exist when the base class constructor is executed:
class Base
{
public:
Base()
{
// Will call Base::I and not Derived::I because
// Derived does not yet exist.
something(I());
}
virtual ~Base() = 0
{
}
virtual int I() const = 0;
};
class Derived : public Base
{
public:
Derived()
: Base()
{
}
virtual ~Derived()
{
}
virtual int I() const
{
return 42;
}
};
Instead you could add the arguments to the base class constructor:
class Base
{
public:
explicit Base(int i)
{
something(i);
}
virtual ~Base() = 0
{
}
};
class Derived : public Base
{
public:
Derived()
: Base(42)
{
}
virtual ~Derived()
{
}
};
Or if you're really fond of OOP you could also create a couple of additional classes:
class Base
{
public:
class BaseConstructorArgs
{
public:
virtual ~BaseConstructorArgs() = 0
{
}
virtual int I() const = 0;
};
explicit Base(const BaseConstructorArgs& args)
{
something(args.I());
}
virtual ~Base() = 0
{
}
};
class Derived : public Base
{
public:
class DerivedConstructorArgs : public BaseConstructorArgs
{
public:
virtual ~DerivedConstructorArgs()
{
}
virtual int I() const
{
return 42;
}
};
Derived()
: Base(DerivedConstructorArgs())
{
}
virtual ~Derived()
{
}
};
What you need is two-phase construction. Use the Universal Programmer's cure: Add another layer of indirection.