Yaara Ben-Or
Yaara Ben-Or

Reputation: 21

dynamic_cast inside dervied constructor

I have a base class and derived class and also a BaseType and DerivedType. on the Base class i Have an object (not a pointer) of BaseType. I want on Derived class's constructor to do a dynamic cast from BaseType to DerivedType.

class DerivedType: public BaseType{};

class Base{
    BaseType basetype; //not a pointer
}

class Derived : public Base{
    Derived(){
        //I want to do in this constructor a dynamic_cast from
        // "basetype" to "DerivedType"
        // when "DerivedType" inherits from "BaseType" also
    }
};

I have both classes class DerivedType: public BaseType class Derived : public Base

On Base class I have an object of BaseType (not a pointer)

and I need on Derived class's constructor to change the type of this object to DerivedType my boss told me to use dynamic_cast

I need to do it because if i'll use class C : public Derived

When i'll use 'basetype' it will be automaticly DerivedType and not BaseType

Upvotes: 0

Views: 255

Answers (2)

James Kanze
James Kanze

Reputation: 153977

One very important point: once an object is constructed, its type is fixed, and can never be changed, regardless. If Base has a member named basetype, that object is constructed by the constructor of Base, before any derived class can access it, and the type of that object is what is declared to be in Base, and can never be changed. You can use dynamic_cast on it (e.g. dynamic_cast<DerivedType&>), but that cast is guaranteed to fail.

It's not clear what you're trying to achieve. Perhaps some variant of the strategy pattern is what you're looking for, where Base::basetype is a pointer or a reference to an object passed into Base::Base() by Derived::Derived(). Or perhaps it's really the value of basetype which should change, which is no problem. (This is what the name suggests.) Describe what you are trying to achieve, and we can perhaps find a solution.

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66441

You can't change the type of the member basetype, whether by using dynamic_cast or any other means.
If your boss told you to do it, they're either very wrong or didn't communicate clearly enough what you should do. I would recommend that you ask for clarification.

One common way to implement this (i.e. a member whose type depends on a subclass) is by turning the base class into a template, passing the member's type as a parameter:

template<typename MemberType = BaseType>  // Default type is BaseType
class Base{
    MemberType something;
}

class Derived : public Base <DerivedType>
{
      Derived()
      {
          // 'something' has type DerivedType
      }
};

Upvotes: 2

Related Questions