Calling Method/Function outside a Class but on the same namespace in c++

NEP 21 Reputation points
2022-07-13T03:09:26.287+00:00

I have a very simple and yet complicated (atleast for me) question on how to call a method/function outside a class but on a same namespace in c++.

I know that you need to create an instance of an object before you can call a method which is inside a class, something like:

namespace Cars {  
  
    public ref class MyClass  
    {  
       void Honda(int i)  
       {  
       //some code  
       }  
     }  
  
    void Register()  
    {  
      MyClass c;  
      c.Honda(1);  
  
      //some code  
  
    }  
  
}  

But how do I do the opposite? Like how do I call Register() inside the MyClass::Honda function if they are on the same namespace but not on the same class?

I tried Cars::Register() but it gives an error saying that Register() is not a member of "Cars".

Thanks!

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,855 questions
0 comments No comments
{count} votes

Accepted answer
  1. Minxin Yu 12,676 Reputation points Microsoft Vendor
    2022-07-13T05:57:19.613+00:00

    Hi, @NEP

    namespace Cars {  
        void Register()  
        {  
            Console::WriteLine("hello");  
            //some code  
      
        }  
      
        public ref class MyClass  
        {  
        public:  
            void Honda(int i)  
            {  
                Register();  
                //some code  
            }  
        };  
      
    }  
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.