Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ virtual functions

Tags:

c++

virtual

Just wondering, what would be fastest? If I had a base class like this

Class Base
{
virtual void Draw()
{
//something...
}
};

Then I would have an array of Base like this:

Base Array[255];

Which could contain both Base and it's derivatives. This would be one way of for example, storing various drawing commands. (I know this would seem java-like, but it's just for the example. Classes with just one function doesn't make much sense.)

Now alternatively, if I knew exactly what derivatives I would make it could be done like this

class Base
{
int ID;
};

then an array of Base like before: Base Array[255];

And then create the Draw functions in the derivatives:

class Der1 : Base
{
void Draw()
{
}
};

class Der2 : Base
{
void Draw()
{
}
};

Now, this solution of course doesn't allow me to just loop through the array and call Draw for each object. Instead it would have to be done something like this.

void CallDraw()
{
for (int i = 0; i < 255; i++)
{
switch(Array[i].ID)
{
case 1: //Der1
   ( (Der1) Array[i] ) . Draw(); 
case 2: //Der2
   ( (Der2) Array[i] ) . Draw();
}

And yeah, to those who have read so far, the actual question. Which would be faster, if you knew the derivatives? Making an organized system yourself, or using virtual functions?

And are there other things to take into consideration? (code cleanness maybe, but I rather like to show off what my class type is in the code, so I'm not bothered by the casts.

like image 753
Andreas Mieritz Avatar asked Feb 27 '23 13:02

Andreas Mieritz


1 Answers

Definitely use virtual functions, that's precisely what they are for. Reimplementing it yourself is error-prone and certainly isn't going to be faster.

Also, in your declaration of Array you need to use pointers:

Base *Array[255];

Otherwise, in C++ (unlike Java), the array could only contain instances of Base and no objects of derived classes. Using a pointer is more like Java's references and allows you to put instances of derived class into the array.

like image 138
Greg Hewgill Avatar answered Mar 08 '23 08:03

Greg Hewgill