Here in this code, "ob" doesn't work after the conditions, and that's because it has been created inside those blocks.
Is there a way to receive the type from the user and then be able to use that specific type of object "outside" its creation block, as well?
#include <iostream>
usingnamespace std;
class Ob
{
public:
virtual ~Ob(){};
virtualvoid foo(){ cout << "Hi, I'm a basic Ob\n"; }
};
class Obi : public Ob
{
int i;
public:
Obi( int i_ ) : i(i_){}
~Obi(){};
void foo(){ cout << "Hi, I'm an int with value " << i << '\n'; }
};
class Obd : public Ob
{
double d;
public:
Obd( double d_ ): d(d_){}
~Obd(){};
void foo(){ cout << "Hi, I'm a double with value " << d << '\n'; }
};
int main()
{
Ob *p;
int n;
cout << "Enter 1 for int, 2 for double: "; cin >> n;
switch( n )
{
case 1: p = new Obi(5); break;
case 2: p = new Obd(12.5); break;
default: p = new Ob; break;
}
p->foo();
delete p;
}
#include <iostream>
#include <typeinfo>
usingnamespace std;
class Ob
{
public:
virtual ~Ob(){};
virtualvoid foo(){ cout << "Hi, I'm a basic Ob\n"; }
};
template<typename T> class ObT : public Ob
{
T value;
public:
ObT( T v ) : value(v) {}
~ObT(){};
void foo(){ cout << "Hi, I'm a " << typeid(T).name() << " with value " << boolalpha << value << '\n'; }
};
int main()
{
Ob *p;
int n;
cout << "Enter 1 for int, 2 for double, 3 for char, 4 for bool: "; cin >> n;
switch( n )
{
case 1: p = new ObT<int> (5 ); break;
case 2: p = new ObT<double>(12.5); break;
case 3: p = new ObT<char> ('A' ); break;
case 4: p = new ObT<bool> (true); break;
default: p = new Ob; break;
}
p->foo();
delete p;
}
That is, for every data and function in ObT, we need its alike name in Ob.
For every function member or data member that you intend to address by a base-class pointer, yes. But you can have data members (e.g. value in the above example) that aren't in ob. And many of the functions may not depend on type: you could simply define them once in the base class and let the templated classes inherit them.
Perhaps you could say what your intended application is: it may not be the appropriate way of solving the problem anyway.
Modern Fortran has the concept of an "unlimited polymorphic type", but I'm not sure that there is anything like it in c++.