简体   繁体   中英

Inherited template class member tests fine in chain constructor, but is “lost” thereafter

My base class, class Foo , is a template class which has the following constructor:

//Declarations
template <class T>
class Foo
{
public:
    Foo::Foo(std::string& root);
    MemberClass obj;
}

template <class T>
Foo<T>::Foo(std::string& root)
{
    MemberClass obj(root); // initialize the member object
    obj.getRoot(); // Prints the string
    // ...
}

It has a child class, which is constructed like so:

template <class T>
Bar<T>::Bar(std::string& root)
    : Foo<T>(root)
{
    //...
}

template<class T>
void
Bar<T>::accessObj()
{
    this->obj.getRoot();
    // Prints the empty string
}

This gives unexpected behaviour, even though no errors are generated. In this case, getRoot() will return the empty string.

I have tested this by altering the Foo constructor like so:

{
    MemberClass obj(root);
    std::cout << &obj << std::endl;
}

and the Bar constructor like so:

//...
    : Foo<T>(root)
{
    std::cout << &this->obj << std::endl;
}

The output gives two different locations in memory, which is totally blowing my mind. Why is this the case? How do I fix it?

Your constructor might better look like this:

template <class T>
Foo<T>::Foo(std::string& root)
    : obj(root) // initialize the member object
{
    obj.getRoot(); // Prints the string
    // ...
}

Before, you were constructing a temporary obj in your Foo constructor and throwing it away, never initializing your member variable at all.

If you're using GCC, the option -Wshadow might have helped catch this mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM