简体   繁体   中英

Accessing Base class protected data member vector in derived class give error 139

It may have been answered somewhere, but I could not find the correct words to search.

I have base class

class B
{
    protected:
        std::vector<int> v;
    public:
        B(): v{} {}
        void test()
        {
            v.push_back( 10 );
            std::cout << v[0] << std::endl; // prints 10
        }
};

child class

class C: public B
{
    public:
        C() {}

       void print() { std::cout << v[0] << std::endl; } // error here

};

main function

int main() 
{ 

    B b;
    b.test(); // initialized vector 10

    C c;
    c.print(); // error 139 here

    return 0; 
}

If I initialize vector in base constructor no error.

B(): v{ 10 } {}

I cannot figure out why? I may doing something really stupid, - assist me on error, I really appreciate it.

b and c are different instances and the vector v doesn't have any elements by default. Reading v[0] in this state is reading out-of-range and will cause error.

The B::test() function pushes something to the vector, so calling it will eliminate this error.

int main() 
{ 

    B b;
    b.test(); // initialized vector 10

    C c;
    c.test();  // call this to have v in c have something
    c.print(); // error 139 hear

    return 0; 
}

The error is simply an out-of-bounds violation, and therefore undefined behavior. After this line

C c;

The vector cv is empty. Therefore std::cout << v[0] tries to access an element that doesn't exist.

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