0

Note: Please edit my title.

// Note : A() is present in a MyClass class

void MyClass::A(){void B();}

In this code,I want to define that function B()(Like putting stuffs e.g cout<<"hi") outside of A function,How to do that? main method cannot access "B" function until or unless it runs the A() function (Because before A function,B wasn't exist).How can I do so? I basically have a function "A" present in a class names "MyClass" ,And in that function "A", I've "created" a new function called "B" ,Now i want to "define" that B function outside of A function (Like we define a function from a class outside of the class) ,How can I do so?

  • 2
    Please provide a [mcve] with the desired usage instead of describing the code with words. – Quimby Aug 03 '22 at 09:05
  • 1
    It is not clear what you want. Describe in more detail and provide an [MRE](https://stackoverflow.com/help/minimal-reproducible-example) – Jason Aug 03 '22 at 09:07
  • I think you are looking for this: https://stackoverflow.com/questions/25724787/static-functions-outside-classes – Najzero Aug 03 '22 at 09:09
  • @AnoopRana I think he means declare not create. – john Aug 03 '22 at 09:11
  • @AnoopRana Is that so? It's giving no error if i Declare a function B inside A,But i just want to define that function (Like writing cout<<"Hi"; in it) outside of A function. – PHANTOM DRAGON Aug 03 '22 at 09:12
  • @john Yeah i suspected the same but note OP says that they want to "define that function outside `A`". – Jason Aug 03 '22 at 09:13
  • 1
    @PHANTOMDRAGON This is why you should show what you mean with **code**, not describe what you mean with **words**. Because you are using terminology incorrectly and just confusing everyone. And even when you do use terminolgy correctly it's hard to be certain that is the case. – john Aug 03 '22 at 09:14
  • 2
    @PHANTOMDRAGON To answer the question I think you are asking. If you define a function outside of any class (i..e it's a global function) then there should be no problem calling it from wherever you like. If you are having problems then you should **show** the code you are having problems with. That is the way to get your question answered instead of closed. – john Aug 03 '22 at 09:17
  • It sounds like you want to "hide" a function, making it callable after calling `A`. If so, you could make `B` a private member function and have `A` return a Callable of some sort, e.g. an `std::mem_fn`, or the result of an `std::bind`, `bind_front`, or a lambda, etc. – Hasturkun Aug 03 '22 at 09:56

1 Answers1

-1

Here is how you can define your B function:

void B()
{
    std::cout << "B";
}

Looks straightforward and also works well.

anatolyg
  • 26,506
  • 9
  • 60
  • 134