Exudes
Exudes

Reputation: 103

C++: Changing type of a struct to child type

In a file database.h, I have the following structs:

struct parent {
...
};
struct childA : parent {
...
};
struct childB : parent {
...
};
struct childC : parent {
...
};

I have the following class:

class myClass {
    parent myStruct;
    ...
    myClass(int input) {
        switch (input) {
        //
        // This is where I want to change the type of myStruct
        //
        }
    };
    ~myClass();
}

Essentially, inside the constructor of myClass, I want to change the type of myStruct depending on what input is:

switch (input) {
case 0:
    childA myStruct;
    break;
case 1:
    childB myStruct;
    break;
case 2:
    childC myStruct;
    break;
}

However, I have not been able to find a solution that works for this. How can I change myStruct's type to one of its type's children? Because myStruct needs to be accessible outside the constructor, I want to declare it as type parent in the class's header and change its type to that of the children in the constructor.

Upvotes: 2

Views: 141

Answers (1)

Barry
Barry

Reputation: 303387

You can't change the type of an object. That is immutable.

What you're looking for is a factory to to choose which type of object to create based on its input:

std::unique_ptr<parent> makeChild(int input) {
    switch (input) {
    case 0: return std::make_unique<child1>();
    case 1: return std::make_unique<child2>();
    ...
    }
}

Upvotes: 7

Related Questions