Hi..
My code is as follows :-

class Class1
{
};
class class2
{
};

main()
{
 ....
.....
 if(var==true)
 class1 c1=createandmanipulate(file);
 else
 class2 c1=createandmanipulate(file);
......
.....
.....
}

How should i declare the createandmanipulate() function so that it can return the respective object i.e either of Class1 or Class2 depending on the value of variable "var"at runtime. Also i know it can be done using template but how. ?? I have no idea.. Plz help

I think this might work.

#include <iostream>

using namespace std;

class Class1 { };
class Class2 { };

// Specialize two type traits for picking class 1 and class 2.
template <bool>
class ClassType { };

template <>
class ClassType<false> { };

// Overload createandmanipulate to use the type traits.
Class1 createandmanipulate( ClassType<true> ) {
  cout<<"Returning Class1\n";
  return Class1();
}

Class2 createandmanipulate( ClassType<false> ) {
  cout<<"Returning Class2\n";
  return Class2();
}

// It all works! :)
int main() {
  Class1 c1 = createandmanipulate( ClassType<true>() );
  Class2 c2 = createandmanipulate( ClassType<false>() );

  return 0;
}

>> ... depending on the value of variable "var"at runtime. Also i know it can be done using template ...

an option would be to use run-time polymorphism.

class base { virtual ~base() = 0 {} };

class Class1 : public base {} ;

class class2 : public base {} ;

base* createandmanipulate( ifstream& file );

int main()
{
  //....
  //.....
  base* object = createandmanipulate(file);
  if( var==true )
  {
    class1* c1 = dynamic_cast<class1*>(object) ;
    assert(c1) ;
    // use c1
  }
  else
  {
    class2* c2 = dynamic_cast<class2*>(object) ;
    assert(c2) ;
    // use c2
  }
  //....
  //.....
  delete base ;
}

use an if/else with dynamic cast only if virtual functions cannot meet your requirements.

>>an option would be to use run-time polymorphism.
I thought about that too but dismissed it because it may not work. createandmanipulate() still has to know whether to allocate an object of type Class1 or Class2 before returning. If it allocates an object of only base then the caller will not get what it expects.

>> If it allocates an object of only base
base
has a pure virtual destructor, the function will not be able to instantiate (a standalone) object of that type.
however, it could return 0; perhaps indicating an error of some kind.

This article has been dead for over six months. Start a new discussion instead.