mercredi 7 août 2019

Initialization of an aggregate containing vectors of base and derived objects

Consider the following:

#include <vector>

class Base {
public:
    Base() : x(0) {}
    int x;
};

class Derived : public Base {
public:
    Derived(double z0) : Base(), z(z0) {}
    double z;
};

class Foo {
public:
    // How to specify a default value for parameter vec0,
    // consisting of two Base objects?
    Foo(std::vector<Base> vec0 = ???) : vec(vec0) {}
    std::vector<Base> vec;
};

class Bar {
public:
    // foo1.vec needs to be initialized with two Base objects.
    // foo2.vec needs to be initialized with two Derived objects.
    Bar() : foo1(???), foo2(???) {}
    Foo foo1;
    Foo foo2;
};

int main() {
    Bar bar;

    // Code here will want to use Base class pointers to access the elements
    // in bar.foo1.vec and bar.foo2.vec.
 }

  1. How to specify a default parameter in the Foo constructor?

  2. In the Bar constructor initializer list, how to specify a vector of Base objects for foo1, and a vector of Derived objects for foo2?

  3. How to title this question so others needing to solve this problem can find it?

Aucun commentaire:

Enregistrer un commentaire