Re: great c++ question
--nextPart5353168.bp75zfUaJN
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8Bit
John Harrison wrote:
John Harrison wrote:
Bobba Dobba wrote:
Amar Kumar Dubedy wrote:
implement a c++ class such that it allows us
to add data members at runtime.
sure it's possible, still you need to access them, and know their
types. all
feasible.
a void pointer kan be used, or if you know the type you can make an
abstract
base class and inherit classes from that. save in whatever for later
access. Still, as I see it there needs to be some kind of "known"
interface
that you can use for accessing.
Show us some code. I don't see how anything you've said above relates to
adding data members at runtime.
Data members have a type, and a name, they are accessed with a
particular syntax. All of these are features of source code, not of a
running program. The question doesn't amke sense unless it is a trick
question.
Of course of the question had been, 'write a class so that you can add
arbitrary data at runtime' it would be much easier. But the question
said data members, not data.
--nextPart5353168.bp75zfUaJN
Content-Type: text/x-c++src; name="main.cpp"
Content-Transfer-Encoding: 8Bit
Content-Disposition: attachment; filename="main.cpp"
#include <iostream>
#include <vector>
class AbstrBase
{
public:
virtual void run()=0;
};
class Int:public AbstrBase
{
int m_i;
public:
void setI(int i)
{
m_i = i;
};
const int& getI()const
{
return m_i;
};
void run()
{
std::cout << "Value is of type integer" << std::endl;
std::cout << "Value is=" << m_i << std::endl;
};
};
class Str:public AbstrBase
{
std::string m_s;
public:
void setS(const std::string s)
{
m_s = s;
};
const std::string& getS()const
{
return m_s;
};
void run()
{
std::cout << "Value is of type string" << std::endl;
std::cout << "Value is=" << m_s << std::endl;
};
};
class Container:public std::vector<AbstrBase*>
{
};
int main(void)
{
Container c;
Int * a = new Int;
a->setI(1);
Str * b = new Str;
b->setS(std::string("hello world!"));
c.push_back(a);
c.push_back(b);
std::vector<AbstrBase*>::iterator it = c.begin();
while(it != c.end() )
{
(*it)->run();
it++;
}
return 0;
}
--nextPart5353168.bp75zfUaJN--