-
Class Constructors
Hi, Im not sure bout the following question, i think i might be being lazy and not reading things i should. Anyway could anyone plz tell me the point of using non-default constructors in some cases over using member functions and leaving the compiler to put in the default constructor and destructor.
-
consider:
Code:
class something
{
int data_;
public:
int & data;
something(void)
: data_(0), data(data_)
{
}
};
int
main(void)
{
something a, b = a;
cout << a.data << endl;
b.data = 1024;
cout << a.data << endl;
}
b's default constructor assigns the reference to a's data!
-
oh, is using constructors the only way data can be copied to other objects?
-
no, of course not. the declaration:
something a, b = a;
resolves to:
something a, b(a);
-
would this task be difficult without constructors?
-
It would be more than difficult :) reference members must be initialised by the constructor's initialiser list, Since you cannot reassign a reference variable.
-
>> could anyone plz tell me the point of using non-default constructors in some cases over using member functions
In general, you want to initialize an object with all the data it needs as soon as you can. If you do it with member functions, this means that there is a point at which the object is not correctly initialized (between the call to the default constructor and the calls to the member functions to set the data). It also means that when somebody is using the class, they might forget to call the member functions and their class instance will be unintialized.
By using a constructor to set the values, you are combining the creation and initialization into a single step, and your class instance always has valid values. There are only a few cases where you want to postpone initialization and use a member function, most of the time you want to do it together.
-
Ty for explanations. Im just about to approach a chapter in
"C++ Without Fear" which is dedicated to constructors so perhaps i shall learn more there provided im in the right mindset when i read (sometimes i let it all go over my head, lol)