Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading