简体   繁体   中英

parameterized object initialization in another class

Am not sure whether I am going in the correct track or not. I need to initialize a parameterized object inside another class, but am not sure how to do this. To make my point clear the code snippet is

class base
{
private:
   bool data_present;
    public:
    /*base()
    {
    cout<<" base :default constructor called"<<endl;
    data_present = false;
    }*/
    base(bool present )
    {
    data_present = present;
    }

    bool present()
    {
    return data_present;
    }
};

class derived :public base
{
    private:
    int _value;
    public:
    /*derived()
    {
    cout<<" derived :default constructor called"<<endl;

    }*/
    derived(int value):base(1)
    {
    _value = value;
    }
};

class test
{
   public:
    test(int data )
    {
    cout<<"test: parameter's constructor "<<endl;
    }
    derived return_data()
     {
     return d;
    }

   private:
     derived d;
};

int main()
{
  test t(100);
  return 0;
}

My intention is to initialize the derived parameterized constructor in test constructor so that value of 100 will be populated in _value.Can anybody please help me on this.

You could use member initialize list to initialize non-static member variable with specified constructor, just like what you do in class derived 's constructor for base subobject.

class test
{
   public:
    test(int data ) : d(data)
                    ~~~~~~~~~
    {
    cout<<"test: parameter's constructor "<<endl;
    }
    derived return_data()
     {
     return d;
    }

   private:
     derived d;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM