vendredi 26 mars 2021

c++ grandchild does not see the data of an abstract grandparent [duplicate]

The following C++ code does not compile:

class Val
{
protected:
    int n;
public:
    Val() : n(0) {}
    Val(int nn) : n(nn) {}

    virtual int blah() const = 0;
};

template <class T>
class subVal : public Val
{
public:
    subVal() : Val() {}

    int blah() const { return n; }
};

template <class T>
class subsubVal : public subVal<T>
{
public:
    subsubVal() : subVal<T>() {}

    int blah() const { return n; } // this is the "faulty" line

    int blahblah() const { return n; }
};



subsubVal<int> ssv;   // declare an instance, to confirm that it can be done

The compiler (VisualStudio) says "C2065 'n' undeclared identifier".

If I replace the line marked "faulty" with

int blah() const { return Val::n; } // replacement line

then it compiles ok.

The failure is, I think, related to the fact that Val here is an abstract class, since another way to get successful compilation is to comment out the pure virtual function declaration of blah() in class Val. Note that the grandchild method blahblah() does not generate a compiler error. I think also it is something to do with the templating, in that the code compiles if one removes the templating (but of course I want to template in the full project; this is just a snippet to illustrate the point). Note also that the child has no problem in seeing the data value n in the parent. It is just the grandchild that does not see it unaided.

I am hoping first for an answer that clarifies the logic (since my code that did not compile looks logical to me), and then for a solution better than sticking lots of horrible 'Classname::' identifiers all over the code of the grandchild. (In practice those identifiers will have longer names and will greatly reduce the naturalness and readableness of the code).

Aucun commentaire:

Enregistrer un commentaire