I have problems with object slicing. I am passing a Derived instance as a parameter in my constructor. Because member variable "base" is copy constructed from this object, it is sliced - it is no longer of type Derived. How can I retain that type without using pointers?
#include <iostream>
#include <string>
class Base
{
public:
virtual ~Base() {};
};
class Derived : public Base
{
public:
~Derived() {};
};
class MyClass
{
public:
MyClass(int x, Base base) : x(x), base(base)
{
if (!dynamic_cast<Derived*>(&(this->base)))
std::cout << "This is not a Derived instance.";
};
int x;
private:
Base base;
};
int main()
{
MyClass myclass(7, Derived());
}
As you can see, this->base is no longer of type Derived but I would like it to be it. Is this possible?
Forgetting for a moment that a reference to a polymorphic class will probably compile to a pointer, you can't do everything with a reference that you can with a pointer. For example, have an array of references/pointers.
The problem with references is that if I pass object by reference to instance of my class, this object must outlive the instance. Then, for example I could not use code like this:
1 2 3 4
int main()
{
MyClass myclass(7, Derived());
}
I can't construct Derived in-place, because it gets freed after living constructor...