Is there a virtual constructor?

I encountered a problem like this in my project:

I designed a base class:

1
2
3
4
5
6
class base {
public:
    std::vector<double> value;
    base():value(3, 0) {}
    virtual ~base()=default;
}


and then I find I need a derived class, and this derived class is nothing different from base except the dimension of the vector value is not 3 but 6, like this:


1
2
3
4
5
6
7
8
9
10
11
12
class derived:public base {
public:

    derived():value(6, 0) {}//Option 1: I believe this is not possible to go through
    
    derived():base() {//Option 2: how about this?
        for(int i=0; i<3; ++i) {
            value.push_back(0);
        }
    }
    virtual ~base()=default;
}


is option 2 possible?

How would you design a hierachy to accomplish this? Thanks.
do you think
Last edited on
Do you really need a hierarchy if the only variation is in the size of the vector?

To let derived class authors have a say in how the base class subobject is initialised, provide a protected constructor.

For instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct base
{
    base() :  values(3) {}
    
    virtual ~base() = default ;

    // ...

    std::vector<double> values ;

    protected: base( std::size_t n, double v = 0 ) : values(n,v) {}

};

struct derived : base
{
    derived() : base(6) {}

    // ...
};
Thanks, JLBorges!

I guess I need the hierarchy, I thought it twice, the member function is a little different. Suppose I do need the hierarchy, is my method of expanding it through push_back() a good way? Is there any better way to do this?


I searched web about your method of protected constructor, it is said it is used for abstract class. I don't want my base member objects to be initialized, that is true. But I have some real-working functions in the base class. Does this still count as an "abstract class"?

Is it necessary to have a constructor like base() : values(3) {} in an abstract class?
Last edited on
> I searched web about your method of protected constructor, it is said it is used for abstract class.

It can be used for any class - abstract or not - that is designed to be inherited from. It is a constructor that can be used only by derived class authors.


> But I have some real-working functions in the base class. Does this still count as an "abstract class"?

It is an abstract class if it has a pure virtual member function. Otherwise, it isn't.
http://en.cppreference.com/w/cpp/language/abstract_class


> Is it necessary to have a constructor like base() : values(3) {} in an abstract class?

It could be useful to have a default constructor (non-trivial, user-defined default initialisation) even for an abstract class.
Topic archived. No new replies allowed.