Search code examples
c++arraysinheritanceconstructorcomposition

Constructor of a children class that have an array that contains objects of another class


Dialog.h

#include "WBasic.h"
#include "WButton.h"
#include "WData.h"

#ifndef WDIALOG_H_INCLUDED
#define WDIALOG_H_INCLUDED


class WDialog : public WBasic
{

    private:
    WButton wB;
    WData wD;


    public:
    //Constructor
    WDialog(const int& e = 0, const WButton& = WButton(0,0), const WData& = WData(0,0,0));

    ~WDialog();

};


#endif // WDIALOG_H_INCLUDED

Dialog.cpp

#include <iostream>
#include "WDialog.h"


WDialog::WDialog(const int& e, const WButton& WBUTTON, const WData& WDATA) :
WBasic(e), wB(WBUTTON), wD(WDATA)
{
}

The code above works great, however I'm trying to make "WButton wB" a vector changing it to"WButton wB[3];"

class WDialog : public WBasic
{

    private:
    WButton wB[3];
    WData wD;

};

But then I've no idea how deal with the Constructor.


Solution

  • You can use vector to solve this problem. I have written a small example below.

    #include <iostream>
    #include <vector>
    using namespace std;
    
        class A{
    
        };
        class B{
            public:
                B():vec (4,A())
                {
                }
            private :
                vector<A> vec;
        };
        int main() {
            // your code goes here
            B obj();
    
            return 0;
        }
    

    You can observe how I have initialized vector vec with three class A object.