Click to See Complete Forum and Search --> : Calling the no-argument constructor


kaftab
October 18th, 2001, 10:13 AM
Hi Gurus:

I am using an older compiler for this program (HP- C++, not HP aCC) on a unix machine. The problem that I see is that when I use the no-arguments constructor, the object does not get created. I see this any time I try to make an object from a no-argument constructor. Although it doesn't make any sense, I think its a compiler "feature". Does someone know about it?

Here's some sample code:


// Class Definition
class UgPartDes
{
private:

// Attributes
RWCString fileName;
RWCString dxfType;
RWCString ptpType;

public:

// Constructors
UgPartDes() { cout << "here" << endl;}
UgPartDes(RWCString dummy) {cout << dummy << endl; }

// Accessor Methods
RWCString getDxfType() { return dxfType; }
RWCString getPtpType() { return ptpType; }
}


// This returns a compile error, since data does not get created
logical NamedRef::readData()
{

UgPartDes data();
cout << "dxftype = " << data.getDxfType() << endl;
cout << "ptptype = " << data.getPtpType() << endl;

return true;
}

// This compiles, but doesn't return the cout statement inside the
// constructor, suggesting that the constructor was never entered
logical NamedRef::readData()
{

UgPartDes data();
return true;
}
// This works
logical NamedRef::readData()
{

UgPartDes data("test");
cout << "dxftype = " << data.getDxfType() << endl;
cout << "ptptype = " << data.getPtpType() << endl;

return true;
}

Paul McKenzie
October 18th, 2001, 12:12 PM
Here is your problem, and it has nothing to do with the compiler version. It has everything to do with your confusion of the syntax of declaring a function and calling the default constructor of an object:

/ This compiles, but doesn't return the cout statement inside the
// constructor, suggesting that the constructor was never entered
logical NamedRef::readData()
{
UgPartDes data(); // This declares a function called "data" that has no arguments, and returns a UgPartDes object!!

// This is the corrected version that instantiates an object
UgPartDes data; // No parentheses!!
return true;
}



The rule is *never* write code that calls the no-argument constructor by using parentheses! This does not call the constructor, instead it declares a function. The only time to use parentheses when calling a no-argument constructor is if you are dynamically creating the object.

logical NamedRef::readData()
{
UgPartDes* pData = new data( ); // Ok
}



Regards,

Paul McKenzie

kaftab
October 18th, 2001, 12:18 PM
Thanks, this helped. I got my syntax mixed up with Java.

Kamran