C++Guns – RoboBlog

15.08.2014

polymorphic objects can live on the stack

Filed under: Allgemein — Tags: — Thomas @ 19:08

Polymorphie kennt ihr ja, Grundzüge von OO;
Im groben geht das ja so


class Base {
  public:
  virtual void func() {
     cout << "Base\n";
  }  
};

class Derived : public Base {
  public:
  virtual void func() {
    cout << "Derived\n";
  }  
};

int main() {
  Base *p = new Derived();
  p->func();  // print "Derived"
}

Ich habe ein Pointer vom Type Base und dennoch wird die Funktion von Derived aufgerufen.
Das hier funktioniert allerdings auch:


int main() {  
  // We dont need to create the object on the heap with new
  // Base *p = new Derived();
  
  // Allocate this object on the stack
  Derived d;   
  Base *p = &d;
  p->func(); // prints "Derived" and not "Base"
}

Objekte auf dem Stack werden wesentlich schneller allokiert als auf dem Heap. Das müsste ein deutlichen Geschwindigkeitsvorteil für kleine und kurzlebende Objekte sein.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress