mehdi_bm
mehdi_bm

Reputation: 409

pass Attribute of a class as input parameter of a function of the class in cpp

Considering a class as

#include <iostream>

class myClass
{
   public:
     int x;
     int y;
     myClass(int _x, int _y): x{_x}, y{_y}{}
     void foo(int z) { std::cout << z;}
};

int main()
{
   myClass my_class(2,3);
   my_class.foo(my_class.x);
}

which means in object of a class, a function of the class is called by passing attribute of the class. it compiles and works for the simple example. But would it make any problem?

Upvotes: 0

Views: 1011

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122595

No there is no problem. foo takes its argument by value, it makes a copy. Maybe it helps to see it like this which is almost equivalent:

int main()
{
   myClass my_class(2,3);
   int a = my_class.x;
   my_class.foo(a);
}

Or view it like this, you are basically asking: Is it a problem to pass the value 2 to foo? No.

Upvotes: 1

Related Questions