Re: abstract class and some questions
10 =D1=84=D0=B5=D0=B2=D1=80=D1=83=D0=B0=D1=80=D0=B8 2014, =D0=BF=D0=BE=D0=
=BD=D0=B5=D0=B4=D0=B5=D0=BB=D0=BD=D0=B8=D0=BA, 18:54:18 UTC+2, Stuart =D0=
=BD=D0=B0=D0=BF=D0=B8=D1=81=D0=B0:
on 02/07/14, Todor Atanasov wrote:
Hi guys, it is me again.
I have entered more deep in C++ and I have reached at a point at which =
my knowledge is a bit....let say limited:)
This is what I want to do:
To have a CArray (just a array, could be vector, list) with objects, th=
at can be a different classes, but all of them have one method process;
In java this is done with abstract class and then type cast, for exampl=
e
abstract class Base
{
public abstract void process();
}
class Floor extends Base
{
public void process();
}
and for the loop I can have
List<Floor> objects = new ArrayList<Floor>();
for (int i = 0; i < objects.size(); i++)
{
objects.get(i).process();
}
but how to make that in C++
Here you go:
#include <vector>
#include <iostream>
// Note: No keyword "interface" in C++, interfaces are just
// classes that only contain pure virtual methods.
class Base
{
public:
// Note: The keyword "virtual" is needed in C++. In Java
// all methods are virtual. The "= 0" is the
// C++ way of saying that the method is abstract.
virtual void process() = 0;
};
class Floor : public Base
{
public:
virtual void process() {
std::cout << "I'm a floor, and I am being processed.";
}
};
int main () {
std::vector<Base*> container;
container.push_back(new Floor());
for (int i = 0; i < container.size(); i++)
{
container[i]->process();
}
}
Disclaimer: I intentionally left out anything related to memory
management. Above program will leak memory. A proper production code
interface should have a virtual destructor as well (there are very very=
rare cases where this is not necessary), so that the objects can be
cleaned up properly.
I can make the two classes with Base having a pure virtual method proce=
ss.
But how to make the cast of Base to Floor. To me that is impossible bec=
ause how would the compile knows how to do it.
You don't need to cast the object to the actual sub-type in order to
access their methods. That's what virtual method have been designed for.
The purpose of all that is that I need to process objects from differen=
t classes and I don't know how to do it.
Regards,
Stuart
LOL thank you VERY MUCH. I really didn't expect that detailed explanation. =
Too bad Google Groups don't have rating, you sir would have gotten 10tp :)