Do I have to break this java habit when using C++?

Started by
45 comments, last by Zahlman 18 years, 5 months ago
Well I have a habit in java, which is using the same variable names as arguments to a function/contructor as the class has(sorry if I'm not saying it right), here's a simple example of what I'm trying to do:

class Date
{
        int d;
public:
        Date (int d);
};

int main()
{
        Date  date = Date(1);
        return 0;
}

Date::Date(int d)
{
        this.d=d;
}

what I'm trying to do is set the member of Date called d to the d passed to the constructor, this gives me the error: date.cpp:16: error: request for member 'd' in 'this', which is of non-class type 'Date* const' Is there a way to do this, or will I have to completely break this habit?
Advertisement
this->d = d;
You would use "this->d" instead of "this.d"; but it's still a trifle unclear to the casual reader what you mean. It's generally a good idea to use different names for arguments than for member variables for the sake of clarity.

EDIT: Beaten to the fruit-flavored alcoholic beverage, as usual.
{[JohnE, Chief Architect and Senior Programmer, Twilight Dragon Media{[+++{GCC/MinGW}+++{Code::Blocks IDE}+++{wxWidgets Cross-Platform Native UI Framework}+++
yes
Of course when using anything other than a builtin type you're better off using the initialiser list:
class Date{		int d;	public:		Date(int d);};int main(){	Date date(1);	return 0;}Date::Date(int d)	:	d(d){}

Enigma
Quote:Original post by TDragon
EDIT: Beaten to the fruit-flavored alcoholic beverage, as usual.


"SiCrane" is a fruity beverage?? Google doesn't say anything.

Feeble attempt to justify this post: As you can probably tell from the ->, in C++ this is a pointer to the object instead of a reference as is the case in Java.
Quote:Original post by load_bitmap_file
Quote:Original post by TDragon
EDIT: Beaten to the fruit-flavored alcoholic beverage, as usual.


"SiCrane" is a fruity beverage?? Google doesn't say anything.


I understood it as a general state of affairs.



jfl.
You will have no problem doing this in Java. I do this in C# all of the time, and Java will be no different.
Well it is a bad habit after all.
------ XYE - A new edition of the classic Kye
punch
n.
A beverage of fruit juices and sometimes a soft drink or carbonated water, often spiced and mixed with a wine or liquor base.

I was beaten to the punch.
{[JohnE, Chief Architect and Senior Programmer, Twilight Dragon Media{[+++{GCC/MinGW}+++{Code::Blocks IDE}+++{wxWidgets Cross-Platform Native UI Framework}+++

This topic is closed to new replies.

Advertisement