Is this pointer required to be used in template inheritance?

  • Thread starter Alessandro [AkiRoss] Re
  • Start date
A

Alessandro [AkiRoss] Re

Hello there,
I was trying this code:

#include <iostream>

template <typename T>
struct Base {
protected:
T value;
};

template <typename T>
struct Derived: public Base<T> {
void set(const T &d) {
this->value = d; // Must be referred using this
}
void get() {
//std::cout << "Value: " << value << std::endl; // ERROR
}
};

int main() {
Derived<int> d;
d.set(5);
d.get();
}

In the Derived::get() method, g++ tells me that value isn't in that
scope. While in set() it is, because I'm accessing it using the this
pointer.
Why is it necessary? It isn't required if the classes aren't
templates.

Thanks
 
A

Alf P. Steinbach

* Alessandro [AkiRoss] Re:
Hello there,
I was trying this code:

#include <iostream>

template <typename T>
struct Base {
protected:
T value;
};

template <typename T>
struct Derived: public Base<T> {
void set(const T &d) {
this->value = d; // Must be referred using this
}
void get() {
//std::cout << "Value: " << value << std::endl; // ERROR
}
};

int main() {
Derived<int> d;
d.set(5);
d.get();
}

In the Derived::get() method, g++ tells me that value isn't in that
scope. While in set() it is, because I'm accessing it using the this
pointer.
Why is it necessary? It isn't required if the classes aren't
templates.

I don't think the language rule is /necessary/, but it provides some safety that
the code has only one possible meaning and that that is the indtended meaning.

I.e. for the general case it's practical.

Consider:


<code>
#include <iostream>

template< typename T > class Base;

static int const value = 666;

template< typename T >
class Derived: public Base<T>
{
public:
void foo() const
{
std::cout << value << std::endl;
std::cout << this->value << std::endl;
}
};

template<>
class Base<double>
{
protected:
int value;
public:
Base(): value( 42 ) {}
};

int main()
{
Derived<double>().foo();
}
</code>


<output>
666
42
</output>


Instead of "this"-qualification you might use class name qualification or a
"using" declaration.

Cheers & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top