Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a static method of another class

I have a class, lets say CAppPath which has a static method:

public:     static CString GetAppPath(); 

and in CAppPath.cpp it's defined as:

CString CAppPath::GetAppPath() {      return "C:\..\MypAth"; } 

Now I have another class CXMLHandler, and I have included CAppPath.h in it. But how do I call the GetAppPath() method? I've tried:

#include "CAppPath.h" void CXMLHandler::MyMethod { CNDSClientDlg->GetAppPath(); } 

but it doesn't work. How should I access this method? Since it is a static method, do I need to create a object of the class or should I make the class itself static?

like image 412
Simsons Avatar asked Dec 06 '10 11:12

Simsons


People also ask

How do you call a static method in a class?

Calling Static FunctionIt is invoked by using the class name. For example: Math. sqrt(a); //calling the square root function of the Math class.

How do you call a static method from another class in C++?

By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.


1 Answers

You only need to use the scope resolution operator :: to qualify the method with the name of the class that exposes it:

CString appPath = CAppPath::GetAppPath(); 
like image 195
Frédéric Hamidi Avatar answered Sep 28 '22 01:09

Frédéric Hamidi