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

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

  3. Magnus Jonneryd

    Pete C Guest

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

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:
    6,021
  2. CoolPint
    Replies:
    8
    Views:
    1,262
    Jeff Schwab
    Dec 14, 2003
  3. Simon White
    Replies:
    2
    Views:
    427
    Sharad Kala
    Jun 16, 2004
  4. JKop
    Replies:
    3
    Views:
    685
  5. Dave
    Replies:
    3
    Views:
    484
    tom_usenet
    Aug 10, 2004
  6. hdixon
    Replies:
    3
    Views:
    877
    hdixon
    Jul 9, 2006
  7. Replies:
    1
    Views:
    357
    Victor Bazarov
    Sep 6, 2005
  8. recover
    Replies:
    2
    Views:
    1,062
    recover
    Jul 25, 2006
Loading...