-5
class A  {
private:
    char a;
    char sub_f(char *);
public:
    A();
    char f(char* ) {some actions using sub_f(char*);}  
};

class B {
private:
    char b;
public:
    B();
    void execute() { b = f("some text");}  //PROBLEM IS HERE
}

Can smb explain me how can I call f(char *) function which is a member of class A, from the void B::execute() ? I can't compile it right now. If I make f(char*) a friend function of the class A, there is another problem appear : friend f(char*) doesn't know anything about private function sub_f(char*) . I am a beginner in C++ and will be appreciate for full answers with explanation.

  • 1
    `'some text'` is not the correct syntax for a string literal (you need double quotes `"some text"`). Also it is incorrect to pass around string literals as `char*`, you should at least use `const char*` or preferably `std::string` – Cory Kramer Jul 03 '17 at 14:31
  • 2
    To call a (non-`static`) method of another class you need an *instance* of that class first – UnholySheep Jul 03 '17 at 14:33
  • ok, let it be double quotes. But the problem is about how to call `f()` function from execute one? – Valentin Tatarenko Jul 03 '17 at 14:34
  • 1
    Please read a good C++ book, here's a list of recommended ones: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – UnholySheep Jul 03 '17 at 14:35

1 Answers1

0

If you have a public member function, like

class A  {
public:
    char f(char* );// {some actions using sub_f(char*);}  
};

you can call it on an instance

A a;
char just_one_char = a.f("Whatever");

The same applies across the board - to call this member function you need an instance.

One approach would be to make your class B have a member variable of type A:

class B {
private:
    char b;
    a a;
public:
    B();
    void execute() { b = a.f("some text");}  //PROBLEM Solved
};

If f doesn't need any instance data from class A it could be static, or a free function.

Perhaps there isn't a one-to-one relationship between B and A like this. Perhaps execute could make an A when it needed to:

class B {
private:
    char b;
public:
    B();
    void execute() {
        A a;//just needed for this function call, rather than lifetime of B
        b = a.f("some text");  //PROBLEM is solved a different way
   }
};
doctorlove
  • 18,872
  • 2
  • 46
  • 62