-4

I'm writing a class A with a member m.
I wanted the member variable to have a default (derived) type, but which could optionally be changed in the class constructor to another (derived) type. Something like

// A.h
class A
{
    DefaultType m {0};
};


// A.cpp
A::A()
{
    // if this is present, change m
    m = OtherType(1., 2.);

    // otherwise, leave as default
}

Sorry I wasn't very clear the first time, tried to simplify the question and may have made it unintelligible.
The context is that I'm exposing the constructor of A to the user, which is supposed to write the constructor, compile the code and run it. The rest of the implementation of A is in a separate file, not user-accessible. Some of the member functions of A defined there will need to access m.fun(), which is a common method to DefaultType and OtherType.

So the constraint is that I want the syntax within the constructor to be as simple as possible. If the user writes the constructor but simply leaves out the (re)definition of m, then the program will just consider it to be of the default type, and use .fun() from that class. Otherwise, m will be of OtherType and .fun() will come from there.

Added to this, there will be some 10 other members like m.
I wanted to know if something like this is possible or if I'll have to rethink the whole design.

joaoFaria
  • 123
  • 1
  • 4

1 Answers1

0

You can do this:

class Base
{
    virtual ~Base() {}
};

class DefaultType : public Base
{
};

class OtherType : public Base
{
};

class A
{
public:
    A(bool use_default = true)
    {
        if (use_default)
            m.reset(new DefaultType());
        else
            m.reset(new OtherType());
    }
    std::unique_ptr<Base> m;
};
John Zwinck
  • 239,568
  • 38
  • 324
  • 436