Sign in to follow this  

C++ Template Inheritance (accessing base member)

This topic is 2338 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi Guys,

I just need a quick C++ template sanity check. The following code compiles successfully on GCC:

[code]#include <iostream>

using namespace std;

template <typename Type>
class Base
{
protected:
Type value;
};

template <typename Type>
class Derived : public Base<Type>
{
public:
Type getValue()
{
return Base<Type>::value;
}
};

int main(int argc, char** argv)
{
Derived<int> derived;
cout << "Hello " << derived.getValue() << endl;
return 0;
}[/code]

However, if I remove the 'Base<Type>::' part from inside getValue() then it no longer compiles. That is, the code:

[code]#include <iostream>

using namespace std;

template <typename Type>
class Base
{
protected:
Type value;
};

template <typename Type>
class Derived : public Base<Type>
{
public:
Type getValue()
{
return value;
}
};

int main(int argc, char** argv)
{
Derived<int> derived
cout << "Hello " << derived.getValue() << endl;
return 0;
}[/code]

Gives the error:

[code]main.cpp: In member function ‘Type Derived<Type>::getValue()’:
main.cpp:18: error: ‘value’ was not declared in this scope[/code]

This surprises me, as I didn't think you needed to clarify the variable in that way as it is a member of the base class.

If I modify the classes to not be templatised then I don't need the 'Base<Type>::' prefix, so why do I need it in the templated case? Is the mistake elsewhere - maybe I'm doing template inheritance wrong?

Thanks!

Share this post


Link to post
Share on other sites
[font=Arial,][url="http://womble.decadent.org.uk/c++/template-faq.html#type-syntax-error"]http://womble.decadent.org.uk/c++/template-faq.html#type-syntax-error[/url][/font]

Here is some info on that.

Btw You can use:
[code]
return this->value; //compiled for me
[/code]

Share this post


Link to post
Share on other sites
Perfect, thanks for that great link. I'll bookmark that for the future.

Curiously it does appear to work on VS2010 (didn't test that exact example but something similar) so I guess GCC is just a little stricter. At least I now know it's the expected behaviour.

Share this post


Link to post
Share on other sites

This topic is 2338 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this