Sorry not sure if this has been asked before, I really dont know what to look up either. I’m new to C++ from Java. When we want to call a function on an object in Java, we say picture.rotateRight();
Then, in rotateRight(), we’d have something like int height=this.getHeight();. However, how do we do this in C++? I have a method named invertcolors(); and then I have something like:
Image* myImage = new Image();
bool b = myImage->ReadFromFile("in_01.bmp");
myImage->invertcolors();
void invertcolors(){
int width=TellWidth();
int height=TellHeight();
...
}
How do I access myImage from the method definition without actually saying myImage (since that name can later be changed).
Also, the function parameters are non-negotiable.
First of all, your
invertcolors()function definition is a non-member function. Although you’ve declared it inside theImageclass, you haven’t linked the implementation to the class in any way so the compiler thinks its a non-member function. To make it a member ofImage, you need to useImage::invertcolorslike this:You do get
thisin C++, but it’s a pointer so you have to usethis->getHeight()in C++. However, note that it is redundant in this case. As a beginner you’ll probably find the only real use in a method having the same argument name as an attribute. In this case, you’ll need to usethis->height = heightfor example. However, note that C++ has a nice syntax addition here. This code does the same as a simple setter:Note that neither in Java nor C++ is
thisan operator..,->and+are examples of operators.