Thread: Access protected base class template variable

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    3

    Access protected base class template variable

    I am trying to access a protected member variable of a base class template from within the derived class template. My compiler (g++ 4.1.2) complains however:

    test.cc: In member function ‘int Derived<T>::protectedVariable() const’:
    test.cc:14: error: ‘protectedVariable_’ was not declared in this scope
    Why is this considered an error?

    I have browsed through the C++ standard and sofar I have only found confirmation that this code should compile for non-template classes (which indeed it does). As far as templates go however, I did not find anything that could shed light on this error. Did I overlook something?

    Sample code (test.cc) attached.

    Code:
    template <class T>
    class Base
    {
    protected:
    	int protectedVariable_;
    };
    
    template <class T>
    class Derived: public Base<T>
    {
    public:
    	int protectedVariable() const
    	{
    		return protectedVariable_;
    	}
    };
    
    int
    main()
    {
    	Derived<int> derived;
    	
    	int var = derived.protectedVariable();
    	
    	return 0;
    }

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    You'll want to use:
    Code:
    return Base<T>::protectedVariable_;
    Probably has to due with template instantiation rules - but I'll defer to someone else on where the standard addresses this

    gg

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    I think "14.6.2 Dependent Names" in the (draft) standard covers it.

    gg

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    So it does. Personally, I prefer prefixing stuff from the base class with this->, not base_name::. That's necessary, for example, to properly resolve virtual calls.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    This was also discussed recently, here.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  2. using class as template variable
    By hiya in forum C++ Programming
    Replies: 17
    Last Post: 04-19-2005, 04:17 AM
  3. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  4. Prime Number Generator... Help !?!!
    By Halo in forum C++ Programming
    Replies: 9
    Last Post: 10-20-2003, 07:26 PM
  5. include question
    By Wanted420 in forum C++ Programming
    Replies: 8
    Last Post: 10-17-2003, 03:49 AM