Suppose your program contains the following class definition (along with
definitions of the member functions):
class YourClass
{
public:
YourClass(int new_info, char more_new_info);
YourClass( );
void do_stuff( );
private:
int information;
char more_information;
};
Which of the following are legal?
YourClass an_object(42, 'A');
YourClass another_object;
YourClass yet_another_object( );
an_object = YourClass(99, 'B');
an_object = YourClass( );
an_object = YourClass;
Let's analyze each statement to determine if it is legal:
YourClass an_object(42, 'A');
an_object
of type YourClass
and calls the constructor YourClass(int new_info, char more_new_info)
with arguments 42
and 'A'
to initialize its member variables information
and more_information
.YourClass another_object;
another_object
of type YourClass
and calls the default constructor YourClass()
to initialize its member variables information
and more_information
.YourClass yet_another_object( );
yet_another_object
of type YourClass
and calls the default constructor YourClass()
to initialize its member variables information
and more_information
. Note that the parentheses ()
are optional here.an_object = YourClass(99, 'B');
YourClass
using the constructor YourClass(int new_info, char more_new_info)
with arguments 99
and 'B'
, and then uses the assignment operator =
to assign the temporary object to the an_object
.an_object = YourClass( );
YourClass
using the default constructor YourClass()
and then uses the assignment operator =
to assign the temporary object to the an_object
.an_object = YourClass;
YourClass
to the object an_object
, which is not allowed. It should provide arguments to call a constructor or use the default constructor if no arguments are needed.In summary, the legal statements are:
YourClass an_object(42, 'A');
YourClass another_object;
YourClass yet_another_object();
an_object = YourClass(99, 'B');
an_object = YourClass();
The last statement (an_object = YourClass;
) is not legal and should be avoided.