• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
D.V.D

Abstract Class Deriving Upwards

9 posts in this topic

Hey guys,

 

I have a question regarding casting abstract classes to their derived counterparts. I'm trying to upcast from the base class to the derived class but both classes are encapsulated in smart pointers. Here's an example:

#include <memory>
#include <string>

	class Shape
	{
		//std::string * type;
		virtual int Area ();
	}

	class Box : public Shape
	{
		//char * m_pBuffer;
		virtual int Area ();
	}

	int Box::Area ()
	{
		return 2;
	}

	int test ()
	{
		std::shared_ptr <Shape> pShape (new Box ());
		std::shared_ptr <Box> pBox = static_cast <std::shared_ptr <Box>> (pShape); // no conversion
		std::shared_ptr <Box> pSecondBox = pShape; // no conversion

		Shape * pStrongShape = new Box ();
		Box * pStrongBox = static_cast <Box*> (pStrongShape); // works
	} 

In the test function, at the beginning, i'm trying to upcast from Shape to Box by using the static_cast but I get an error telling me that there is no suitable conversion between the two. I can't use dynamic_cast either since it tells me to dynamic cast, the type must be of type pointer. What would be the proper way of achieving this using smart pointers? Shouldn't static casts do the conversion properly for me? Or am I forced to convert between normal pointers to smart pointers in order for this to work? 

Edited by D.V.D
0

Share this post


Link to post
Share on other sites

Unfortunately, I use Visual Studio 2010 which doesn't seem to support it. Do I have to use dynamic cast in this case at all? Why can't it be static?

0

Share this post


Link to post
Share on other sites

Typically, static cast is used on pointer types or for int->float types of conversions. std::shared_ptr<T> is not a pointer type (even though you use it as if it were a pointer). It's technically an object, and since there is no conversion operator between std::shared_ptr<T> and std::shared_ptr<T_Derived> static_cast can't be used. That's why your compiler complains about there being no suitable conversion between the two types. It simply doesn't know how to turn the base shared_ptr into the derived shared_ptr. As far as the compiler is concerned those types are completely unrelated.

 

I'm not a huge expert on C++ managed pointer types, so I might be wrong about this, but I'm pretty sure there isn't much you can do without getting the raw pointer from the shared_ptr object and dynamic/static/whatever-you-want casting that to the type you want. After you do your dynamic cast, do you intend to keep the dynamic casted pointer around? If not, you likely don't need the dynamic casted pointer to be inside a shared_ptr object. You can just use the raw pointer and then discard it.

1

Share this post


Link to post
Share on other sites

I'm trying to upcast from the base class to the derived class

This is downcasting, not upcasting. And you really shouldn't do it.

 

Every time you downcast, you are admitting that your design is flawed such that the program cannot infer the type of the object in question. While downcasts are unavoidable in some languages (such as pre-generics Java), in a modern language there is no good excuse for violating the Liskov substitution principle like that.

Edited by swiftcoder
2

Share this post


Link to post
Share on other sites
Hello, thanks for the responses. The reason why i'm doing this cast is because of my resource manager and how its laid out. I'm not really sure if there is a better way to make it but in essence, I have 3 classes. A resource loader class which is abstract, a resource data class which is abstract, and the resource manager which holds a map of strings to resource data shared pointers as well as a list of resource loaders. THe resource manager is meant to abstract all file loading of different types to one interface. So to get a resource, I call getresource member which picks the appropriate resource loader for my file, loads it into a shared ptr to IResourceData (the derived version for that file type for example, textfile data) and returns that from the calling function. The downcast is sort of required because you have a bunch of derived classes from ResourceData but you need to have a common way of expressing all of them to store them in a map and to give them to the user after calling get resource. I could use templates but the syntax is ugly plus it achieves the same thing as casting in the first place.
0

Share this post


Link to post
Share on other sites

I consider a pointer cast more ugly than a nice typesafe template :) . But static_pointer_cast should work in VS10.

 

My resource system has improved drastically by deviding it to respectively one resource cache by resource type.

1

Share this post


Link to post
Share on other sites

Okay I'm attempting to use templates now (never used them before) to get everything working but I'm getting a ton of errors regarding standard c++ files. So I have my Resource Manager and implementation over here for a text file:

//Resource Manager.h
	
	class IResource
	{
	protected:
		std::string m_filePath;

	public:
		virtual ~IResource () = 0;

		virtual bool VLoad (const std::string & sourcePath) = 0;
		virtual void VUnLoad () = 0;
	};

	class ResourceManager
	{
		std::map <std::string, IResource*> m_ResourceMap;
	public:

		template <class TResourceType>
		TResourceType* GetResource (const std::string & sourcePath)
		{
			if ( m_ResourceMap[sourcePath] != 0 )
			{
				return dynamic_cast <TResourceType*> (m_ResourceMap[sourcePath]);
			}

			TResourceType * pNewResource = new TResourceType();

			pNewResource->VLoad(sourcePath);
			m_ResourceMap[sourcePath] = pNewResource;
			return pNewResource;
		}
	};

//TextFile.h

	class TextFile : public IResource
	{
	private:
		char * m_pBuffer;
		std::string m_filePath;

	public:
		~TextFile ();

		virtual bool VLoad (const std::string & filePath);
		virtual void VUnLoad ();
		char* GetReadOnlyBuffer ();

	private:
		int GetFileSize (const std::string & filePath);
	};

//TextFile.cpp

#pragma once

#include "Text File.h"

	TextFile::~TextFile ()
	{
		if ( m_pBuffer != nullptr )
		{
			VUnLoad();
		}
	}

	bool TextFile::VLoad (const std::string & filePath)
	{
		m_filePath = filePath;
		unsigned int fileSize = GetFileSize(m_filePath);
		std::ifstream loadedFile (m_filePath, std::ios::in | std::ios::binary | std::ios::ate);

		//assert(fileSize > 0);
		//assert(m_pBuffer != nullptr);

		m_pBuffer = new char [fileSize];

		if ( loadedFile.is_open() )
		{
			loadedFile.seekg(0, std::ios::beg);
			loadedFile.read(m_pBuffer, fileSize);
			loadedFile.close();
		}

		//assert(loadedFile.fail());

		return true;
	}

	void TextFile::VUnLoad ()
	{
		//assert (m_pBuffer == nullptr);
		delete[] m_pBuffer;
		m_filePath = "";
	}

	char* TextFile::GetReadOnlyBuffer ()
	{
		return m_pBuffer;
	}

	int TextFile::GetFileSize (const std::string & filePath)
	{
		std::ifstream in(filePath.c_str(), std::ifstream::in | std::ifstream::binary);
		in.seekg(0, std::ifstream::end);
		return (int)(in.tellg()) + 1;
	}

The implementation is just a derivation of IResource which allows me to load and manipulate text files. I'm calling this from my main function like this:

		m_ResourceManager = ResourceManager ();

		TextFile * pTextFile = m_ResourceManager.GetResource<TextFile> ("test.txt");
		printf(pTextFile->GetReadOnlyBuffer()); //Make sure the file is loaded properly
		delete pTextFile;

I'm getting a ton of errors however about some stuff I'm assuming have to do with the parameters in the m_ResourceMap variable in Resource Manager:

1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtree(1885) : see declaration of 'std::operator <'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(124) : while compiling class template member function 'bool std::less<_Ty>::operator ()(const _Ty &,const _Ty &) const'
1>          with
1>          [
1>              _Ty=std::string
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\map(71) : see reference to class template instantiation 'std::less<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=std::string
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtree(451) : see reference to class template instantiation 'std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,_Mfl>' being compiled
1>          with
1>          [
1>              _Kty=std::string,
1>              _Ty=IResource *,
1>              _Pr=std::less<std::string>,
1>              _Alloc=std::allocator<std::pair<const std::string,IResource *>>,
1>              _Mfl=false
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtree(520) : see reference to class template instantiation 'std::_Tree_nod<_Traits>' being compiled
1>          with
1>          [
1>              _Traits=std::_Tmap_traits<std::string,IResource *,std::less<std::string>,std::allocator<std::pair<const std::string,IResource *>>,false>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtree(659) : see reference to class template instantiation 'std::_Tree_val<_Traits>' being compiled
1>          with
1>          [
1>              _Traits=std::_Tmap_traits<std::string,IResource *,std::less<std::string>,std::allocator<std::pair<const std::string,IResource *>>,false>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\map(81) : see reference to class template instantiation 'std::_Tree<_Traits>' being compiled
1>          with
1>          [
1>              _Traits=std::_Tmap_traits<std::string,IResource *,std::less<std::string>,std::allocator<std::pair<const std::string,IResource *>>,false>
1>          ]
1>          c:\users\documents\visual studio 2010\projects\test\resource manager.h(20) : see reference to class template instantiation 'std::map<_Kty,_Ty>' being compiled
1>          with
1>          [
1>              _Kty=std::string,
1>              _Ty=IResource *
1>          ]
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtree(1885) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xtree(1885) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\list(1588) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\list(1588) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\list(1588) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2582) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2582) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::unique_ptr<_Ty,_Dx> &,const std::unique_ptr<_Ty2,_Dx2> &)' : could not deduce template argument for 'const std::unique_ptr<_Ty,_Dx> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory(2582) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(1356) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(1356) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(1356) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(1179) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(1179) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(1179) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(318) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(318) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const std::string'
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\utility(318) : see declaration of 'std::operator <'
1>c:\program files (x86)\microsoft visual studio 10.0\vc\include\xfunctional(125): error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator

Is it because of the way I am initializing a new template type in GetResource that causes these errors? 

Edited by D.V.D
0

Share this post


Link to post
Share on other sites
For the compiler error, did you remember to add the line #include <string> to the file? That is where string's operator< is located.

You need to include the string class in your resource manager header file so it knows how to expand the std::map template.
1

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  
Followers 0