user2601570 user2601570 - 1 month ago 9
C++ Question

not declare in scope when compiled g++

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()'

Answer

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() {
    // ...
}
Comments