class templates + inheritance

Hi,

I'm trying to run the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

template <class T>
class A
{
public:
    A(int a): x(a) {}
protected:
    int x;
};

template <class T>
class B: public A<T>
{
public:
    B(): A<T>::A(100) {cout << x << endl;}
};

int main()
{
    B<char> test;
    return 0;
}

But g++ says me "error: ‘x’ was not declared in this scope". Why?

thanks in advance
Last edited on
It's probably because you don't have int x defined in the file before you are trying initialize it with the constructor. Just switch them and it should work fine.
thanks for your answer, but I think that's not the problem. Note that the following version of the code above works fine:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

template <class T>
class A
{
public:
    A(int a): x(a) {}
protected:
    int x;
};

template <class T>
class B: public A<char>
{
public:
    B(): A<char>::A(100) {cout << x << endl;}
};

int main()
{
    B<char> test;
    return 0;
}

I simply changed the template parameters. But what is wrong with my previous code?
Last edited on
Try replacing from B constructor 'x' with this->x
thanks, that works! But why do I have to use "this"?
Last edited on
Your compiler may not recognise 'x' to be a local of 'B' as it isn't declared there but it is for sure a 'B' member. The value pointed by this has the member 'x' so it solves that problem.
But why does it work when I replace A<T> by A<char> or something else? Is there no way to avoid having always to use a this-pointer? The given code is only an example demonstrating the problem. All these this-pointers in my real program would make my code quite unreadable.
"x" is not a member of B...it is technically a member of A so when you use a method of B to access x the compiler may not be able to find it. However when you use "this" it is a pointer to the current class which will lead to it being able to find "x" as a member inherited from A. Hope that makes sense.
But why does it work when I replace A<T> by A<char> or something else?????
I have just tried to compile my code with g++-3.3 instead instead of g++-4.3 - and it works!
Topic archived. No new replies allowed.