Home > Net >  Creating a pointer to a class in a function belonging to a different class
Creating a pointer to a class in a function belonging to a different class

Time:11-22

I'm trying to populate a vector of type pointer to class B, which I'll be using later. When I try to read the vector's element, the value I'm getting is different from what I've given. Can someone please help me here, what mistake I'm making and how to correct it? Thanks

#include <iostream>
#include <vector>

class B {
    public:
    int b;
    B (int n) {
       b = n;
    }
};

std::vector<B*> v;

class A {
    public:
    int a;
    void func(int n);
};

void A::func(int n) {
    B obj_b(n);
    B* ptr = &obj_b;
    v.push_back(ptr);
}

int main() {
    A obj_a;
    obj_a.a = 5;
    obj_a.func(4);
    std::cout<<obj_a.a<<std::endl;
    for (auto it:v) {
        std::cout<<it->b<<std::endl;
    }
}

The output I'm getting is: 5, 32765 Whereas the expected output is: 5, 4

CodePudding user response:

Using value instead of pointer, as per the comments above:

#include <iostream>
#include <vector>

class B {
    public:
    int b;
    B (int n) {
       b = n;
    }
};

std::vector<B> v;

class A {
    public:
    int a;
    void func(int n);
};

void A::func(int n) {
    v.emplace_back(n);
}

int main() {
    A obj_a;
    obj_a.a = 5;
    obj_a.func(4);
    std::cout<<obj_a.a<<std::endl;
    for (auto& e:v) {
        std::cout<<e.b<<std::endl;
    }
}

CodePudding user response:

You can use heap allocations and take advantage of std::unique_ptr<T>. Here is the fix:

#include <iostream>
#include <vector>
#include <memory>


class B
{
public:
    B ( const int n )
    {
       b = n;
    }

    int b;
};

std::vector< std::unique_ptr<B> > v; // use a vector of B pointers
                                     // ( std::unique_ptr<B> )
class A
{
public:
    void func( const int n );

    int a;
};

void A::func( const int n )
{
    v.push_back( std::make_unique<B>( n ) ); // returns a pointer object of type
}                                            // std::unique_ptr<B>

int main ()
{
    A obj_a;
    obj_a.a = 5;
    obj_a.func( 4 );
    std::cout << obj_a.a << std::endl;

    for ( const auto& ptrB : v )
    {
        std::cout << ptrB->b << std::endl; // use -> operator to have access to
    }                                      // ptrB's members

    return 0;
}

Hopefully, this helps.

  • Related