• Advertisement
Sign in to follow this  

Making a copy of object from a pointer but dont know its type

This topic is 1376 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello.

In the main where i make a copy of above objects(bellow that comment) i don't know how to determinate what type the object it is so i wrote (a) for this example

[code]
class a
{
public:
    virtual void Print();
};

class b : public a
{
public:
    void Print();
};

class c : public a
{
public:
    void Print();
};
//////////////////////////////////////////
void a::Print()
{
    std::cout<<"a"<<std::endl;
}
void b::Print()
{
    std::cout<<"b"<<std::endl;
}
void c::Print()
{
    std::cout<<"c"<<std::endl;
}
//////////////////////////////////////////
int main()
{
    std::unique_ptr<a> objA1 = std::unique_ptr<a>(new b);
    std::unique_ptr<a> objA2 = std::unique_ptr<a>(new c);
    //Make a copy of above objects
    std::unique_ptr<a> objA3 = std::unique_ptr<a>(new a/*this a i do not know to to determinate its type*/(*objA1));
    std::unique_ptr<a> objA4 = std::unique_ptr<a>(new a/*also this a i do not know to to determinate*/(*objA2));

    objA1->Print();
    objA2->Print();
    objA3->Print();
    objA4->Print();

    system("pause");
    return 0;
};
[/code]

Output is

b
c
a
a

But i need it to be (b c b c) how can i achieve that?

Share this post


Link to post
Share on other sites
Advertisement
The general solution is to add a 'virtual a* clone() const' function and require that every subclass implements it correctly.

Share this post


Link to post
Share on other sites

You can even automate the process of defining the clone-methods by adding a intermedia templated class:

class a
{
public:

	virtual a* Clone(void) = 0;
	virtual void Print();
}

template<typename Class>
class a1 : public a
{
public:

	a* Clone(void) const override final
	{
		return new Class(*this);
	}
}

class b : public a1<b>
{
public:

	void Print();
}

class c : public a1<c>
{
public:

	void Print();
}

This can be usefull in reducing redundant code, since many/all implementations of clone will probably just call the classes copy-ctor in the first place, specially if you have many classes that derive from "a".

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement