C ++ call a method of a public parent class through its derived class object

I have a base class which I have defined as follows:

namespace yxs
{
    class File
    {
    public:
        File(std::string fileName);
        virtual ~File();
        bool isExists();
        size_t size();

    protected:
        std::string fileName;
        std::ifstream* inputStream;
        std::ofstream* outputStream;
}

      

Then I created a child class that inherits the base class:

namespace yxs
{
    class InputFile : File
    {
    public:
        InputFile(std::string fileName);
        virtual ~InputFile();
    };
}

      

From another unrelated class, I created an instance of the child class and tried to call the method: isExists()

void yxs::Engine::checkFile()
{
    bool isOK = this->inputFile->isExists(); // Error on compile in this line

    if(!isOK)
    {
        printf("ERROR! File canot be opened! Please check whether the file exists or not.\n");

        exit(1);
    }
}

      

However, the application will not compile. The compiler gave two error messages:

Engine.cpp:66:34: 'isExists' is a private member of 'yxs::File'

and

Engine.cpp:66:17: Cannot cast 'yxs::InputFile' to its private base class 'yxs::File'

These errors also came up when I tried to call the method size()

.

Why did this error happen? In the concept of inheritance, it's allowed to call a method of a parent class from its child, isn't it?

+3


source to share


1 answer


You need to change it from private to public inheritance:

class InputFile: public File

      



Without a public keyword, all members of the file become private members of InputFile.

+6


source







All Articles