RedShirt
RedShirt

Reputation: 864

c++: function cannot be overloaded

I am encountering a compile time error with the following output:

$ g++ -ggdb `pkg-config --cflags opencv` -o `basename main.cpp .cpp` main.cpp StringMethods/StringMethods.cpp `pkg-config --libs opencv` -std=c++0x
In file included from main.cpp:2:0:
VideoFile.hpp:32:10: error: ‘bool VideoFile::fileExists(const string&)’ cannot be overloaded
     bool fileExists(const std::string & path)
          ^
VideoFile.hpp:15:10: error: with ‘bool VideoFile::fileExists(const string&)’
     bool fileExists(const std::string & path);

However, I do not see how that error makes sense, because I have only function declaration which I directly copied and pasted when writing the definition.

class VideoFile
{
private:
    std::string filePath;
    bool fileExists(const std::string & path);

public:

    VideoFile(const std::string & path)
        :filePath(path)
    {
        filePath = StringMethods::trim(path);
        if (!fileExists(filePath))
            throw std::runtime_error("The file: " + filePath + " was not accessible");
    }

    ~VideoFile() 
    {

    }

    bool fileExists(const std::string & path)
    {
        std::ifstream file(path);
        return file.good();
    }
};

Upvotes: 6

Views: 20468

Answers (4)

HazemGomaa
HazemGomaa

Reputation: 1630

you can't overload fileExists function by another one with the same parameters by just using different scope, as you do in your example .. You may keep the two fileExists functions that you have, but you need to use different parameters , as follows

     class VideoFile
     {
       private:

       bool fileExists();

       public:

       bool fileExists(const std::string & path) // overloading bool fileExists();
       {
         std::ifstream file(path);
         return file.good();
       }
    };

Upvotes: 2

rocambille
rocambille

Reputation: 15996

Because the method is already declared, you must define it outside the class declaration:

class VideoFile
{
    // ...
    bool fileExist(const std::string path);
    // ...
};

bool VideoFile::fileExist(const std::string& path)
{
     // ...
}

Upvotes: 3

molbdnilo
molbdnilo

Reputation: 66459

You can't both declare and define a member function inside the class definition.

(You even made the declaration private and the definition public.)

Either remove the declaration or move the definition outside of the class definition (I recommend the latter).

Upvotes: 14

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

You have fileExists twice in the class itself.Once without definition

 bool fileExists(const std::string & path);

and once with defintion

  bool fileExists(const std::string & path)
{
    std::ifstream file(path);
    return file.good();
}

You have two options either remove the without definition part, or remove the with definition part and provide the definition outside the class.

Upvotes: 5

Related Questions