Search code examples
c++templatesinheritanceintellisense

Is it safe to access a member via child class, if you use templates in C++?


It sounds like a strange question, but when I use the following example code in Visual Studio 2022, IntelliSense is warning me that the member iMember in the parent class is inaccessible, even though the code itself seems ok to me and is running without any problems.

Example Code:

template<class S, class T> class Child;

template<class S, class T>
class Base {
    int iMember = 0;
public:
    Base(const Child<S, T>& child);
    Base(int iMember) : iMember(iMember) {}
    void Print() { std::cout << iMember << std::endl; }
};

template<class S, class T>
class Child : public Base<S, T>{
public:
    Child(int i) : Base<S,T>(i) {}
};

//the following constructor causes the IntelliSense warning that Base<S,T>::iMember is inaccessible 
template<class S, class T>
Base<S, T>::Base(const Child<S, T>& child) : iMember(child.iMember) {}

int main() {
    Child<int, int> cc(234);
    Base<int, int> bb(cc);
    cc.Print(); //prints 234
}

I have no idea why IntelliSense is making this warning, but maybe my code has an undefined behavior.


Solution

  • "but maybe my code has an undefined behavior...."

    The program is well-defined i.e there is no UB in the given code.


    the following constructor causes the IntelliSense warning that Base<S,T>::iMember is inaccessible

    This is a false positive. In the constructor initializer list of the base class, we can safely/correctly write child.iMember because we're in the scope of the base class.