There are two commonly used methods of using the constructor
to initalize data members, so I wondering, purley to improve
my program security, which is safer out of these two methods.
method one:
Code:
class Foo
{
public:
Foo();
private:
int data1;
int data2;
int data3;
};
Foo::Foo() :
data1(0),
data2(10),
data3(100)
{}
method two
Code:
class Foo
{
public:
Foo ( int, int, int );
private:
int data1;
int data2;
int data3;
};
// assume the argument values are passed from main
Foo::Foo ( int d1, int d2, int d3 )
{
data1 = d1;
data2 = d2;
data3 = d3;
}
Thinking again, is calling a set member function on each data
member to initalize more safer? As it would be possible to do this:
Code:
void Foo::setData1 ( int d1 )
{
if ( d1 < 0 )
{
std::cout << "\nPassed value is negative!\n";
}
else
{
data1 = d1;
}
}
I know the above code is not correct in general, but that is the general idea.
I am wondering, which method is considered the most safe for initalizeing data
members?
Any help greatly appreciated!