Abstract Class Deriving Upwards

Started by
8 comments, last by D.V.D 9 years, 10 months ago

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?

Advertisement

If your compiler supports it, you can use the C++11 feature std::dynamic_pointer_cast. It's supported in Visual Studio 2013.

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?

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.


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.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

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.

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.

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?

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.

Well thats embarrassing. Works fine now and loads the file properly :D Thanks a lot!

This topic is closed to new replies.

Advertisement