C++ Class Composition: Constructor? or ()operator? -
i writing code book exercise , ran simple question. best if show examples first.
first class: fclass heaader
class fclass { public: explicit fclass( int = 0, int = 0 ); fclass& operator()( int, int ); void print(); private: int x; int y; }
first class: fclass cpp
fclass::fclass( int a, int b ) : x(a), y(b) { } fclass& fclass::operator()( int a, int b ) { x = a; y = b; } void fclass::print() { cout << "x: " << x << "\ny: " << y << endl; }
second class, sclass.h
class sclass { public: explicit sclass( int = 0, int = 0 ); void print(); private: fclass firstclass; }
second class, sclass.cpp
sclass::sclass( int a, int b ) : firstclass( a, b ) { } void sclass::print() { firstclass.print(); }
the main function
int main() { sclass secondclass( 1, 2 ); secondclass.print(); }
now question when deleted operator() function in fclass. code still worked! understand 'explicit' declaration of fclass's constructor should prohibit sclass's fclass definition in constructor (firstclass( a, b )) because fclass explicitly defined in private member declaration. therefore, re-initialize in sclass firstclass( a, b ), operator function () should defined (as did). why code work without operator() definition?
to add more comments on question, understanding, statement 'firstclass( a, b )' should not call fclass's explicit constructor, because not first time initialized. again, understanding, constructors called when class first initialized construct class. firstclass initialized , constructed in header file...
you confused explicit
keyword , operator()
functions.
the keyword explicit
prevents constructor getting called construct object implicitly. simple example:
let's there function:
void foo(fclass obj) {...}
without explicit
keyword, able call function using syntax:
foo({1, 2});
the arugment {1,2}
used call constructor , resulting object passed foo
.
with explicit
keyword, won't able use that. you'll have use:
foo(fclass{1, 2});
or
foo(fclass(1, 2));
the operator()
function has no relationship explicit
keyword , construction of objects. means, can use:
fclass obj(1, 2); obj(10, 20);
you said:
as understand
explicit
declaration offclass
's constructor should prohibitsclass
'sfclass
definition in constructor (firstclass( a, b )
) becausefclass
explicitly defined in private member declaration.
your understanding not correct.
the line
fclass firstclass;
in definition of class sclass
says class has member variable named firstclass
, type fclass
. doesn't set value of variable when object of sclass
constructed.
in definition of constructor of sclass
, initializing member using : firstclass( a, b )
, right thing do. if skipped it, member initialized if used :firstclass()
, valid way initialize object of type fclass
.