We help IT Professionals succeed at work.

Returning a concrete class via abstract class API

ambuli
ambuli asked
on
Hi there,

I have to return a concrete class instance through a abstract class function.
I have the code as given below.  I want to associate the returnConcrete( ) function with the
IAbstract class somehow... I am not sure if this is possible.
I want to be able to use it in Test.cpp something like

IAbstract * c = IAbstract::returnConcrete( )

Is it possible?
Thanks,

1:
In IAbstract.h
--------------------
class IAbstract
{
   public:
   virtual void somePureVirtualFunc() = 0;

};
IAbstarct * returnConcrete();    <----

In Concrete.h
-----------------
class Concrete : public IAbstrct
{

};

Test.cpp
--------

IAbsract * c = returnConcrete();

Open in new window

Comment
Watch Question

jkr
Top Expert 2012

Commented:
Sure, that is not only possible, that's the usual way to do that, i.e.
class IAbstract
{
   public:
   virtual void somePureVirtualFunc() = 0;

};
IAbstarct * returnConcrete();   



class Concrete : public IAbstrct
{

};

IAbstarct * returnConcrete() {

  return new Concrete; // <----- that's all
}

// ...

IAbsract * c = returnConcrete();

Open in new window

Author

Commented:
Thanks JKR.  yes, that is how I have it.  But, I am thinking that the returnConcrete( ) function when used in Test.cpp should have a scope( what I mean is it appears returnConcrete( ) is a global function when doing it this way.  I want to know if it is possible to have a static method in the IAbstract class itself to return the concrete class instance.

Top Expert 2012
Commented:
Well, that defies the purpose - just think about it, you are defiving from 'IAbstract' and are about to create a static method that uses 'new' for a derived class. Yet it *does* work from a technical point of view:
class IAbstract
{
   public:
   virtual void somePureVirtualFunc() = 0;

   static IAbstract * returnConcrete();   
};




class Concrete : public IAbstract
{

   virtual void somePureVirtualFunc() {};
};

IAbstract * IAbstract::returnConcrete() {

  return new Concrete;
}

// ...

void main () {

  IAbstract * c = IAbstract::returnConcrete();
}

Open in new window

Author

Commented:
Thank you.