Search code examples
c++syntaxreferenceshared-ptrcopy-constructor

C++ shared_ptr copy constructor syntax


I have the following C++ code that I'm trying to get to compile (relevant sections follow). I'm having trouble understanding what's wrong with my syntax.

I get the error

C2664: A(const A&) : cannot convert parameter 1 from A *const to const A&

As I understand it, the *b.getA() should dereference the pointer, giving me the actual object, which I should then be able to copy with the copy constructor.

class A: {
    public:
        A(const &A);
        A();
};

class B: {
    private:
        shared_ptr<A> myA;
    public:
        B() { myA = make_shared<A>(A()); }
        shared_ptr<A> getA() { return myA; }
};

main() {
    B b; // default constructor of B
    A a = *b.getA(); //try invoke copy constructor from A
    // Throws error C2664: A(const A&) : cannot convert parameter 1 from A *const to const A& 
}

Any help is appreciated.


Solution

  • Your copy constructor is incorrect, it should be A(const A&) not A(const &A).

    This compiles fine:

    class A {
        public:
            A(const A&){}
            A(){}
    };
    
    class B {
        private:
            shared_ptr<A> myA;
        public:
            B() { myA = make_shared<A>(); }
            shared_ptr<A> getA() { return myA; }
    };
    
    main() {
        B b; // default constructor of B
        A a = *b.getA();
    }