1

Sample code:

template<typename T, int X>
struct A {
    T a = X;
};

template<int X>
struct B : public A<int, X> {
    int fun() {
        // return A<int, X>::a;  // Method 1
        // return this->a;       // Method 2
        return a;                // Wrong!
    }
};

struct C : public A<int, 564> {
    int fun() {
        return a;                // Correct
    }
};

int main() {
    B<78> b;
    C c;
    std::cout << b.fun() << std::endl;
    std::cout << c.fun() << std::endl;
    return 0;
}

class B & C inherited from class A, which has a public member a.

In class C, we can access a directly, but we cann't do that in class B.

Compiler will raise an error:

error: 'a' was not declared in this scope

My questions are:

  1. Why access a directly in class B is wrong and in class C is correct?

  2. I found two methods to access a in class B, see code snippet above. They both work, but not convenient. I wonder is there any better way to do it?

  • `return A::a;` This works. – kiner_shah Mar 15 '23 at 10:36
  • Related/duplicate: [Why do I have to access template base class members through the this pointer?](https://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-pointer). 1) Because `B` is derived from template and `C` is not (it's derived from specific instantiation, not a template). 2) You can also use `using` directive in class scope: `using B::a;` – Yksisarvinen Mar 15 '23 at 10:37

0 Answers0