Dawson
Dawson

Reputation: 573

Simple function not working when using namespaces

I have the below code that compiles and executes without error, but the line that should be printed in the menu() function is never printed.

Menu.cpp

#include "stdio.h"
#include "Menu.hpp"
#include <iostream>
using namespace std;

namespace View
{
 void Menu::startMenu()
    {
    cout << "2\n";
    }
}

Menu.hpp

#ifndef MENU_H //"Header guard"
#define MENU_H

namespace View
{
class Menu
    {
    void startMenu();
    };
}
#endif

I wrote a simple test to call the menu function, if it works correctly the output should be 1 2 3

but the 2 is never printed.

MenuTest.cpp

#include "Menu.hpp"
#include "stdio.h"
#include <iostream>
using namespace std;

int main()
{
    cout << "1\n";
    View::Menu startMenu();
    cout << "3\n";
}

Can someone see what's going on here?

Upvotes: 2

Views: 103

Answers (3)

billz
billz

Reputation: 45410

View::Menu startMenu();

Declares a function which returns View::Menu type, which is also known as most vexing parse

To initialize an object and call it's member function, you should do:

View::Menu menu;
menu.startMenu();

BTW, you need to make startMenu() function public:

class Menu
{
public:    //<-----
    void startMenu();
};

See live sample. help this helps.

Upvotes: 2

lulyon
lulyon

Reputation: 7225

When substracting the brckets of View::Menu startMenu();, the code

View::Menu startMenu;

is a object definition of View::Menu, which does not call the function Menu::startMenu(). And that is when "cout << "2\n";" is not executed. To call further Menu::startMenu():

startMenu.startMenu();

Upvotes: 1

Egg Head
Egg Head

Reputation: 379

Because you declare function "startMenu()", that is returns type "View:Menu" But you don't call function startMenu().

Try make following code:

View::Menu obj;
obj.startMenu();

PS. And make startMenu() as public:

class Menu
{
    public:
        void startMenu();
};

Upvotes: 1

Related Questions