c++ - Initializing object members inside constructor -


i working on classes in c++ , found out can not initialize objects inside constructor. let me explain:

class rect { public:     rect(float x, float y): m_x(x), m_y(y) {}     float area() {return m_x*m_y;} private:      float m_x;     float m_y; };  class cube{ public:     cube(float x, float y, float z) {         m_r = new rect(z,y);  //this not possible.. why not?         m_z = z;     }     float volume() {return m_r.area()*z;} private:     rect m_r;     float m_z; }; 

to solve this, can either cube(float x, float y, float z) : m_r(x,y), m_z(z) {} or change m_r pointer , assign value m_r = new rect(x,y) how can set value without changing m_r pointer , assign value inside constructor body?

if, whatever reason, want assign m_z in body of constructor instead of initializing it, need 2 things:

1) give rect default constructor. needs because m_z default initialized.

2) assign thus: m_r = rect(z,y);


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -