Can we create derived class object from base?

Can we create derived class object from base?

Answer: No. In general, When we create object of a class, its reference is stored in stack memory and object is stored in heap and address of object is assigned to class reference. Child objch is child class reference created on stack memory.

Can you assign a variable of a derived class to another variable of a derived class of its base class Why or why not?

A derived class reference can be assigned to a base class variable, but a base class reference cannot be assigned to a derived class variable. If a derived class reference is assigned to a base class variable, the variable must be cast back to the derived class before any derived class methods can be called with it.

Which header is used with function objects?

Explanation: header is need to be used with function objects.

How to store derived class objects in base class variables?

Since you ask for a C++ish way of doing this, the right approach is to use a suitable Smart pointer instead of storing a raw pointer in the vector. That will ensure you do not have to manually manage the memory, RAII will do that for you automatically. You’re experiencing slicing.

Can a vector copy a derived class object?

You’re experiencing slicing. The vector copies the derived object, a new one of type Base is inserted. TL;DR: You should not inherit from a publicly copyable/movable class. It is actually possible to prevent object slicing, at compilation time: the base object should not be copyable in this context.

Why are objects of different types stored in the same container?

Fortunately, in C++ there are better alternatives. A better solution would be storing functions and not objects themselves in containers. The common reason why you want to put different types in the same container is to perform the same actions on all of them, for example, Sphere::Draw () or Plane::Draw ().

How to store base class objects in C + +?

By storing a pointer to Base class there would be no slicing and you can achieve the desired polymorphic behavior as well. Since you ask for a C++ish way of doing this, the right approach is to use a suitable Smart pointer instead of storing a raw pointer in the vector.