I have a basic question about OOP. I would like to create a method inside the class which uses 2 objects of this class as arguments and returns a float value based on the attributes of these objects.
public float MyMethod(CMyClass obj1, CMyclass obj2)
When I want to use this method in main() I cannot do it like this:
CMyClass o1 = CMyClass();
CMyClass o2 = CMyClass();
float x = MyMethod(o1, o2);
I cannot see this method because it is related to an object. I can access it like this:
o1.MyMethod(...)
but this does not make sense.
You can declare the method static
, and access it like MyClass::MyMethod
class MyClass {
public:
static void MyMethod(const MyClass & arg1, const MyClass & arg2) {}
};
Since you want to access attribute of those, use a friend function(non member). You can declare it in you class:
friend float MyMethod(CMyClass obj1, CMyclass obj2);
you want
static float MyMethod(CMyClass obj1, CMyclass obj2)
static
keyword here will make the method belong to the class, not an individual instance of the class/object. Access as CMyClass::MyMethod
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With