Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Community » Newbie corner » |SOLVED] Vector of object: cast to inherited class
Re: Vector of object: cast to inherited class [message #52363 is a reply to message #52353] Sat, 14 September 2019 13:41 Go to previous messageGo to previous message
Xemuth is currently offline  Xemuth
Messages: 387
Registered: August 2018
Location: France
Senior Member
Hello Novo, Thanks for you respons.

I have take a look at Array documentation and it say :
Quote:
Array can be also used to store polymorphic elements - stored elements could be derived from T. To store such elements, you pass a pointer to an element previously created on the heap. Still, Array takes over ownership of such element (it e.g. deletes it when appropriate). You can also use this method to create an Array of elements that do not have either pick, deep copy constructor nor default constructor.


"To store such elements, you pass a pointer to an element previously created on the heap"
It mean I must use an Array<A*> ? Their is no way to do something like the exemple bellow without having to work with ptr ?

Thanks in advance, have good day.

#include <Core/Core.h>

using namespace Upp;

class A {
	public:
	A(){}
	virtual ~A(){}
	virtual void Hello(){
		Cout() << "Hello from A" <<"\n";
	}	
};

class B :public A{
	public:
	B(){}
	~B(){}
	void Hello(){
		Cout() << "Hello from B" <<"\n";
	}	
};

CONSOLE_APP_MAIN
{
	Array<A> myArray;
	B b;
	static_cast<B&>(myArray.Add(b)).Hello(); //"Hello from A"
	((B&)myArray.Add(b)).Hello(); //"Hello from A"
	//Looking for "Hello from B" without using Array<A*>
	
	Array<A*> myArray2;
	myArray2.Add(&b)->Hello(); //Working properly but using ptr 
}
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: copying code from web into IDE
Next Topic: Simple way to develope 2D Game
Goto Forum:
  


Current Time: Mon Apr 29 03:02:49 CEST 2024

Total time taken to generate the page: 0.08592 seconds