infoasker
infoasker

Reputation: 17

Destructor protected within this context c++ (issue #1)

I have a compilation error with C++11.

I have defined a base class Node with protected ctor and dtor. I have defined an inherited class Directory with public inheritance.

I am calling the dtor of the base class in the dtor of the inherited class. The compilation failed with the message:

error: 'virtual Node::~Node()' is protected within this context

I really don't understand why, as I was pretty sure that the protected keyword allowed methods (and objects) in a derived class to have access to public and protected methods (and data) of the base class.

Below I have put the code, that I hope has enough comments. The idea is to create a basic fs running in RAM.

Node.hpp

#ifndef NODE_HPP
#define NODE_HPP

#include "FileSystem.hpp"

class Directory;    //Forward declaration of class Directory used in this class
class File;         //Forward declaration of class File used in this class

/*Class representing a node of the fs : a node can be a file or a directory*/
class Node
{
    /*friend class Directory;*/     //Related to the issue #1 : Destructor protected within this context

    protected:
        Node(FileSystem *, int, string, Directory * = nullptr);
        virtual ~Node();
        Node(const Node&);

    ...

#endif // NODE_HPP

Node.cpp

#include "Node.hpp"

Node::Node(FileSystem *fs, int uid, string name, Directory *parent) {
    this->fs = fs;
    this->uid = fs->get_fresh_uid();
    this->name = name;
    this->parent = parent;
}

Node::~Node(){
    fs = nullptr;
    parent = nullptr;
}

...

Directory.hpp

#ifndef DIRECTORY_HPP
#define DIRECTORY_HPP

#include "Node.hpp"
#include "File.hpp"
#include <vector>

/*Class representing a directory of the fs : a directory is a kind of node*/
class Directory : public Node
{
    /*friend class FileSystem;*/ //Related to issue #2 : forward declaration of class Directory

    private:
        Directory(FileSystem *fsys, int id, string n, Directory *par = nullptr);
        virtual ~Directory();
        Directory (const Directory &);
    private:
        vector<Node*> children;             //Vector representing the children nodes of the directory
    ...
};

#endif // DIRECTORY_HPP

Directory.cpp

#include "Directory.hpp"

Directory::Directory(FileSystem *fs, int uid, string name, Directory *parent) : Node(fs, uid, name, parent){
}

Directory::~Directory(){
    for (auto c : children) {
        delete c;   //Related to the issue #1 : Destructor protected within this context
        c=nullptr;
    }
}

...

Upvotes: 0

Views: 329

Answers (1)

infoasker
infoasker

Reputation: 17

Thanks for the comments and the link to the answer.

Upvotes: -1

Related Questions