inheritance - C++ contains relationship - always need initializer list? -



inheritance - C++ contains relationship - always need initializer list? -

if want object contain (a "has-a" relationship). must contained object created in initializer list? want avoid using pointers. if know have utilize initializer list that's fine.

#include <iostream> class { private: int ii; public: a(int anii): ii(anii) {}; int getbilly() {return ii;} void billy() { (int jj = 0; jj < ii; ++jj) { std::cout << "billy!" << std::endl; } } }; class b { private: public: mya; b(int wantii): mya(a(wantii)) { } void snoodly() { int ii = mya.getbilly(); (int jj = 0; jj < 2*ii; ++jj) { std::cout << "silly!" << std::endl; } } }; int main () { b myb = b(5); myb.snoodly(); myb.mya.snerdly(); homecoming 0; }

not really.

a contained object (co) can created default initialisation, class fellow member declaration initialiser, or in constructor's initialiser list. latter 2 needed if co had no default constructor or default value unwanted.

if co's value known , available @ time container constructed convenient initialise co value.

if not, reasonably initialise co harmless default value 1 of above mechanisms, , later set value assignment or method calls, depending on supports.

so reply is: not really, although may quite convenient.

c++ inheritance

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -