Sign in to follow this  
BaneTrapper

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

Recommended Posts

BaneTrapper    1531

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
Juliean    7068

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this