Defining a class member that has required constructor arguments in C++ -
suppose have class foo
constructor has required argument. , further suppose i'd define class bar
has member object of type foo
:
class foo { private: int x; public: foo(int x) : x(x) {}; }; class bar { private: foo f(5); };
compiling give errors (in exact case, g++ gives "error: expected identifier before numeric constant
"). one, foo f(5);
looks function definition compiler, want f
instance of foo
initialized value 5. solve issue using pointers:
class foo { private: int x; public: foo(int x) : x(x) {}; }; class bar { private: foo* f; public: bar() { f = new foo(5); } };
but there way around using pointers?
if have c++11 support, can initialize f
@ point of declaration, not round parentheses ()
:
class bar { private: foo f{5}; // note curly braces };
otherwise, need use bar
's constructor initialization list.
class bar { public: bar() : f(5) {} private: foo f; };
Comments
Post a Comment