jn1kk
jn1kk

Reputation: 5112

C++ Private Function - Not In This Scope Error

I am very new to C++, coming form Java and C. My book does not mention private functions and Google searches don't turn up much. This should be trivial for me, but I can't get it to work.

I have this code:

#ifndef RUNDATABASE_H
#define RUNDATABASE_H
#include <iostream>
#include <string>

class RunDatabase
{
    public:
        int main();
    protected:
    private:
        bool checkIfProperID(std::string);
};

#endif // RUNDATABASE_H

And in another file:

#include "RunDatabase.h"

int main()
{

    std::string id; // after this, I initialize id

    if(!checkIfProperID(id))
    {
        std::cout << "Improperly formatted student ID, must be numeric" << std::endl;
        break;
    }

}

bool RunDatabase::checkIfProperID(std::string id)
{
    return true;
}

I get this error: error: 'checkIfProperID' was not declared in this scope

Using MinGW g++ 4.4.1 on Windows 7 64 bit.

Thanks for any help.

Upvotes: 0

Views: 1205

Answers (3)

rob05c
rob05c

Reputation: 1233

The problem is that main is not implemented as a member of RunDatabase.

int main()
{

should be

int RunDatabase::main()
{

You will then need a main() function, which your program will start execution in.

Also consider not naming your class member functions after the main function which starts execution, to avoid confusion. Example:

class RunDatabase
{
public:
    int execute();
protected:
private:
    bool checkIfProperID(std::string); 
};

int RunDatabase::execute()
{

    std::string id; // after this, I initialize id

    if(!checkIfProperID(id))
    { 
        std::cout << "Improperly formatted student ID, must be numeric" << std::endl;
        break;
    }

}

/// runs when the program starts
int main()
{
    RunDatabase runDatabase;
    runDatabase.execute();
}

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727037

Unlike Java, C++ allows free-standing functions. The main function that is called when you run your program is free-standing main, not a member main. If you modify your cpp file as follows, things should compile:

int main() {
    RunDatabase rdb;
    rdb.main();
}

RunDatabase::main() {
    // the code of the main function from your post
}

Upvotes: 1

Marlon
Marlon

Reputation: 20312

checkIfProperID is a method of RunDatabase. This means you need to have a RunDatabase object in order to call checkIfProperID.

RunDatabase rd;
rd.checkIfProperID(id);

I don't see why the other function is not in the scope.

The "scope" here is the class.

RunDatabase::checkIfProperID

Notice the scope-resolution operator ::. This means that the method belongs to the class, not global scope.

Upvotes: 1

Related Questions