Returning a concrete class via abstract class API

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

ambuliAsked:
Who is Participating?
 
jkrConnect With a Mentor 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

0
 
jkrCommented:
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

0
 
ambuliAuthor 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.

0
 
ambuliAuthor Commented:
Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.