Accessing template base class members in C++

Here is one tricky thing I learned about calling members from a template base class.

In order to access a member (method or field) of a templated base class, you need to either use the “this” pointer or use the explicit name of the base class with template arguments.

template <typename T>
class base {

protected:
    int x;
};

template <typename T>
class derived : public base<T> {

public:
    int f() { return this->x; }
};

int main() {
    derived<int> d;
    d.f();
    return 0;
}

 

without “this->” in front of  “this->x”, it would not be able to find the member. So we have to be careful when using inheritance for templated classes.

The reason is that this makes x a dependent name, so that lookup is deferred until the template parameter is known.

Useful Links

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s