Members and Templates

Discussion in 'C++' started by Magnus Jonneryd, Oct 6, 2005.

  1. 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.


    --
    (Should insert humorous quotation here)
     
    Magnus Jonneryd, Oct 6, 2005
    #1
    1. Advertising

  2. Magnus Jonneryd wrote:
    > 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
     
    Victor Bazarov, Oct 6, 2005
    #2
    1. Advertising

  3. Magnus Jonneryd

    Pete C Guest

    Pete C, Oct 6, 2005
    #3
  4. Magnus Jonneryd, Oct 6, 2005
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JFCM
    Replies:
    4
    Views:
    5,767
  2. CoolPint
    Replies:
    8
    Views:
    1,017
    Jeff Schwab
    Dec 14, 2003
  3. JKop
    Replies:
    3
    Views:
    505
  4. Dave
    Replies:
    3
    Views:
    378
    tom_usenet
    Aug 10, 2004
  5. recover
    Replies:
    2
    Views:
    845
    recover
    Jul 25, 2006
Loading...

Share This Page