|
-
October 18th, 2001, 10:13 AM
#1
Calling the no-argument constructor
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;
}
-
October 18th, 2001, 12:12 PM
#2
Re: Calling the no-argument constructor
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
-
October 18th, 2001, 12:18 PM
#3
Re: Calling the no-argument constructor
Thanks, this helped. I got my syntax mixed up with Java.
Kamran
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|