0

I'm compiling below code and its throwing below error. Can someone have al look and let me know what is wrong here.

// Demonstrate dynamic_cast on template classes.
template <class T>
class Num
{
protected:
    T val;
public:
    Num(T x) { val = x; }
    virtual T getval() { return val; }
};

template <class T>
class SqrNum : public Num<T>
{
public:
    SqrNum(T x) : Num<T>(x) { }
    T getval() { return val * val; }
};
int main()
{
    Num<int> *bp, numInt_ob(2);
    SqrNum<int> *dp, sqrInt_ob(3);
    Num<double> numDouble_ob(3.3);
    bp = dynamic_cast<Num<int> *> (&sqrInt_ob);
    if(bp) {
        cout << "Cast from SqrNum<int>* to Num<int>* OK.\n";
        cout << "Value is " << bp->getval() << endl;
    } else
        cout << "Error\n";
    cout << endl;
    return 0;
}

Error:

DynamicCast.cpp: In member function ‘T SqrNum<T>::getval()’:
DynamicCast.cpp:77:22: error: ‘val’ was not declared in this scope
  T getval() { return val * val; }

As far as I understand I can access protected member of base class in derived.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Prashant Gaur
  • 135
  • 1
  • 1
  • 5

0 Answers0