Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't resolve undeclared identifier C++

Tags:

c++

templates

I am trying to call the Size() function of base class Array. The error from Clang is "use of undeclared identifier 'Size'". Below is my header for NumericArray, function definition in source file, and function definition in base class. Many thanks for the help.

derived header

#ifndef NUMERICARRAY_H
#define NUMERICARRAY_H
#include "array.h"

namespace Cary
{
    namespace Containers
    {
        template<typename T>
        class NumericArray: public Array<T>
        {
        public:
            NumericArray<T>();    //default constructor
            ~NumericArray<T>();    //destructor
            NumericArray<T>& operator = (const NumericArray<T>& array1);    //assignment operator
            NumericArray<T>& operator * (double factor) const;    //scale
            NumericArray<T>& operator + (const NumericArray<T>& array1) const;    //add
        };
    }
}
#endif

function definition in cpp

template<typename T>
        NumericArray<T>& NumericArray<T>::operator * (double factor) const    //scale
        {
            NumericArray<T> scale(Size());
            for (int i = 0; i < Size(); i++)
                scale[i] = factor * ((*this).GetElement(i));
            return scale;
        }

size function from base class

template<typename T>
        int Array<T>::Size() const    //returns size
        {
            return m_size;
        }
like image 359
kits Avatar asked Sep 13 '26 01:09

kits


1 Answers

You need to use this->Size(), this is a bit awkward, but that's how C++ works. When you derive from a template class, the compiler doesn't look at the members of the template base at declaration point (basically, at declaration, the base part is un-instantiated, and it is a bit painful for the compiler to figure out if the function is defined in the base class). So the default behaviour is to not look in in the scope of template base classes.

Alternatively, you can as well use using Array<T>::Size; to tell the compiler that the the base class contains indeed the function Size().

Or, as a last alternative, can explicitly call Array<T>::Size(). However this alternative is not recommended whenever you deal with virtual functions, since you lose the ability to using them polymorphically.

BTW, there is a whole chapter (Item 43) in Effective C++ by Scott Meyers (see The Definitive C++ Book Guide and List) dedicated to this issue.

like image 172
vsoftco Avatar answered Sep 15 '26 15:09

vsoftco