Search code examples
c++shared-ptr

shared pointer isn't working when casting?


casting shared pointer from B class to A class is not working the console output isn't 12 it's (it outputs A's x but i want B's x)(probably an other memory address). what's wrong with my code

#include <iostream>
#include <memory>

class A
{
public:
    int x;
};

class B : public A
{
public:
    B(){}
    B(const B*){}
    int x = 12;
};

std::shared_ptr<A> create()
{
    return std::make_shared<B>(new B);
}

int main(){

   std::shared_ptr<A> p;
   p = create();
   std::cout << p->x << std::endl;

   std::cin.get();
    return 0;
}

Solution

  • A::x and B::x are different objects. Variable access is never polymorphic in C++, so when you access p->x, you're accessing A::x. A::x was never initialized though, so the behavior of your program is undefined.

    You need to either have your derived class's constructor initialize the base class's object or delegate that responsibility to the base class's constructor:

    class A
    {
    public:
        A(int x) : x{x} {}
        int x;
    };
    
    class B : public A
    {
    public:
        B() : A{12} {}
    };
    

    Live Demo


    Alternatively you could wrap x in a virtual accessor method:

    class A
    {
    public:
        virtual ~A() = default;
        virtual int x() const = 0;
    };
    
    class B
    {
    public:
        int x() const override
        {
            return x_;
        }
    private:
        int x_ = 12;
    };
    

    Live Demo