Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method unrelated to an object

Tags:

c++

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.

like image 534
BuahahaXD Avatar asked Oct 15 '12 16:10

BuahahaXD


3 Answers

You can declare the method static, and access it like MyClass::MyMethod

class MyClass {
public:
    static void MyMethod(const MyClass & arg1, const MyClass & arg2) {}
};
like image 100
nogard Avatar answered Oct 02 '22 20:10

nogard


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);
like image 36
RoundPi Avatar answered Oct 02 '22 18:10

RoundPi


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.

like image 31
djechlin Avatar answered Oct 02 '22 19:10

djechlin