Home > Back-end >  Pass instance as an argument to a function and then display the instance data in the function
Pass instance as an argument to a function and then display the instance data in the function

Time:11-15

I want to be able to pass pixelOne as the argument to the showPixelDetails function. The only way I've found of doing it so far is below. How do I pass pixelOne as an argument to that function?

#include <iostream>
#include <string>

using namespace std;

class Pixel
{
public:
    float xCoord;
    float yCoord;
    double brightness;

    void showPixelDetail();

};

void Pixel::showPixelDetail()
{

    cout<< xCoord << endl;
    cout<< yCoord << endl;
    cout<< brightness << endl;

}
int main()
{

    Pixel pixelOne;

    icon myIcon;

    pixelOne.xCoord=1;
    pixelOne.yCoord=1;
    pixelOne.brightness=15;

    pixelOne.showPixelDetail();


    return 0;
}

pixelOne needs to be the argument I pass. When I try to pass it, xCoord, yCoord and brightness aren't declared in the scope. I know why but there must be a way for them to be passed with the pixelOne as the argument.

CodePudding user response:

What you have is fine already, but you seem to want to have a function that accepts a Pixel argument instead of using a member function with implicit this. In that case, move the function outside the class and add a parameter:

class Pixel{
  public:
    float xCoord;
    float yCoord;
    double brightness;
};

void showPixelDetail(const Pixel& pixel) {
    std::cout << pixel.xCoord << '\n';
    std::cout << pixel.yCoord << '\n';
    std::cout << pixel.brightness << '\n';
}

int main() {
    Pixel pixelOne;
    
    pixelOne.xCoord=1;
    pixelOne.yCoord=1;
    pixelOne.brightness=15;

    showPixelDetail(pixelOne);
}

live link

CodePudding user response:

You can't pass an instance of a class as an argument to a function. You can only pass primitive data types (int, float, double, etc.) or pointers to instances of classes.

If you want to be able to pass an instance of a class to a function, you need to create a function that takes a pointer to an instance of that class as an argument. For example:

void showPixelDetails(Pixel* pixel)
{
    cout << pixel->xCoord << endl;
    cout << pixel->yCoord << endl;
    cout << pixel->brightness << endl;
}

int main()
{
    Pixel pixelOne;

    pixelOne.xCoord = 1;
    pixelOne.yCoord = 1;
    pixelOne.brightness = 15;

    showPixelDetails(&pixelOne);

    return 0;
}
  • Related