3

I have encountered the following problem with someone else's code which presumably was compiling at some point. A base class is a generic container of a data member of type T. This data member is protected but is only visible in the derived class' overridden functions when prefixed with this->. The following simplified example replicates the problem on my machine and on the currently distributed version of MinGW included with code::blocks 12.11

Base.h

#ifndef BASE_H
#define BASE_H

template <typename T>
class Base
{
   public:
    void set(T value);
    virtual void show() = 0;
   protected:
    T value;
};

template <typename T>
void Base<T>::set(T value)
{
   this->value = value;
}

#endif

Derived.h

#ifndef DERIVED_H
#define DERIVED_H

#include <iostream>

#include "Base.h"

template <typename T>
class Derived : public Base<T>
{
   public:
    virtual void show();
};

template <typename T>
void Derived<T>::show()
{
    std::cout << value << std::endl;
}

#endif

Compiling a .cpp file which uses Derived.h results in the following error on g++4.6.3:

In file included from main.cpp:3:0: Derived.h: In member function ‘virtual void Derived::show()’: Derived.h:18:15: error: ‘value’ was not declared in this scope

However simply changing std::cout << value << std::endl; to std::cout << this->value << std::endl; fixes the problem. The same behaviour is observed even with data members which are not of type T.

Is this expected behaviour? I imagine not since the legacy code was definitely compiling at some point.

DuncanACoulter
  • 2,095
  • 2
  • 25
  • 38
  • It is expected. Out of curiosity, which compiler was the legacy code compiling with? – juanchopanza Sep 26 '13 at 08:15
  • Oh yes so it does, thanks. I can happily watch this question move towards being closed. I must have phrased my question oddly because none of the suggestions offered by stack overflow included that question or any of its other versions. – DuncanACoulter Sep 26 '13 at 08:16
  • @juanchopanza I believe on one of the Visual Studio compilers although I am not certain. – DuncanACoulter Sep 26 '13 at 08:17
  • 1
    I think VS is non-standard about the two-phase look-up, so it will pass some illegal code (and make other code behave in non-standard ways). – juanchopanza Sep 26 '13 at 08:18

0 Answers0