Members and Templates

  • Thread starter Magnus Jonneryd
  • Start date
M

Magnus Jonneryd

I've been having some fun with templates and ran in to the following:

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

template<typename T = int>
class B: public A<T>{
B(){
a = 1; //*
}

};

If i try to compile this i get a message telling me that "a" is undeclared
but if i change the row (*) to:
this->a
all is well.

Is this due to the fact that the compiler doesn't generate any code for
the template until it is called explicitly? If it is so isn't it odd
that the compiler doesn't realize that "a" is a member of a super class
and then initialize it when I try to assign it a value in a derived class?

Thanks in advance.
 
V

Victor Bazarov

Magnus said:
I've been having some fun with templates and ran in to the following:

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

template<typename T = int>
class B: public A<T>{
B(){
a = 1; //*
}

};

If i try to compile this i get a message telling me that "a" is undeclared
but if i change the row (*) to:
this->a
all is well.

Is this due to the fact that the compiler doesn't generate any code for
the template until it is called explicitly?

No, 'a' in B's scope is called a "dependent name". See FAQ.
> If it is so isn't it odd
that the compiler doesn't realize that "a" is a member of a super class
and then initialize it when I try to assign it a value in a derived class?

It's not so.

V
 

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

Similar Threads

templates?? 2
Templates 5
templates 10
Templates and inheritance 1
Variadic templates std::tuple 2
templates, nesting and using problem 0
Templates and g++ 4
Templates and inheritance 2

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top