Onno
Onno

Reputation: 295

shared_ptr implicit cast failing here and succeeding there?

I have a class MemberBuilder that builds classes derived from Member for me, one of them being CommitteeMember. Member is a base class for a decorator pattern chain of objects that are instances of Member derived classes.

MemberBuilder contains the following method to create a CommitteeMember for me:

std::shared_ptr<CommitteeMember> MemberBuilder::createCommitteeMember(int memberID, int age, QString& name, QString& surName, Committee* committee)
{
    return std::shared_ptr<CommitteeMember> (new CommitteeMember(memberID,age,name,surName, committee));
}

in some method in the same MemberBuilder, it contains the following lines:

std::shared_ptr<Member> result;
result = createNormalMember(memberID, age, name, surName);

and then somewhere further down:

std::shared_ptr<Member> newChild = createCommitteeMember(memberID, age, name, surName, commission);
result->addChild(newChild);

this does not yield any compiler problems.

But if I create a std::shared_ptr mb in some class and then do:

std::shared_ptr<Member> member = getMember(memberID);

std::shared_ptr<Member> newChild = mb->createCommitteeMember(memberID, age, name, surName, commission);
member->addChild(newChild);

getMember has the following interface:

std::shared_ptr<Member> getMember(int memberID);

I get

"conversion from std::shared_ptr<CommitteeMember> to non-scalar type std::shared_ptr<Member> requested"

To me it seems I'm doing exactly the same, except that I call it from within the same class the first time. I can't understand why I'm getting an error the second time if it is accepted in MemberBuilder itself. What am I doing wrong the 2nd time that's not triggering an error the 1st time? IIRC, if would do this with raw pointers, there would not be a problem.

Q: What difference makes it fail the 2nd time?

Upvotes: 2

Views: 605

Answers (1)

tenfour
tenfour

Reputation: 36906

As the error says, you are working with different pointer types. shared_ptr<CommitteeMember> is not the same as shared_ptr<Member>. It's good that you cannot do this conversion, because the reference counts would not be shared and you'd end up with bizarre object lifetime behavour.

In order to statically cast a shared_ptr, look at std::static_pointer_cast<>().

Upvotes: 2

Related Questions