0
votes

This is my A.h file

class A
{
public:
    void menuChoice();
void displaystartingMenu(); //EDIT
};

This is my A.cpp file

#include "A.h"

void displaystartingMenu()
{


    cout<<"Please enter your choice:";


}
void A::menuChoice()
{
    displaystartingMenu();
    cout<<"Hello"<<endl;

}
int main()
{ 
   A a;
   a.menuChoice();

}

i tried to put

void menuChoice();

on the top of my cpp file but it still won't compile . it gives me error

In function ‘int main()’: A.cpp:112:13: error: ‘menuChoice’ was not declared in this scope menuChoice();

How do I compile : g++ A.cpp A.h

By right I don't need to even declare the function of top of the cpp because I have already declare it in my header file and I have included in my .cpp. What went wrong here?

EDIT:

Error :

 In function `A::menuChoice()':
A.cpp:(.text+0x229): undefined reference to `A::displaystartingMenu()'
2
You meant A a; a.menuChoice(); ?songyuanyao
You need an instance of A before you can call functions in A. That's how classes work. If you don't want that then don't use a class.user253751
but what if i have another method() already declared public in the class to be place inside menuchoice(); , do i have to make an instance of A in menuchoice(); as well? if method() is just a cout @immibiswhat
@user2601570 No. Inside a member function, there's a "current instance" of the class, and you can access functions and variables of that instance by default.user253751
@user2601570 That probably means you didn't define it.user253751

2 Answers

3
votes

Option 1: Make an A instance and call that instance's menuChoice method:

#include <iostream>

class A {
public:
        void menuChoice();
};

void A::menuChoice() {
        std::cout << "Hello" << std::endl;
}

int main() {
        A a;
        a.menuChoice();
        return 0;
}

Option 2: Make menuChoice a static method and call it as A::menuChoice:

#include <iostream>

class A {
public:
        static void menuChoice();
};

void A::menuChoice() {
        std::cout << "Hello" << std::endl;
}

int main() {
        A::menuChoice();
        return 0;
}

Edit: Addressing the new problem, when you tried to define A::displaystartingMenu you wrote:

void displaystartingMenu() {
    // ...
}

It must be defined like this:

void A::displaystartingMenu() {
    // ...
}
3
votes

menuChoice is a non static member function of class A. In order to call it you need to instantiate an object A, as follows

int main()
{
  A a;
  a.menuChoice();

  return 0;
}