[c++] C++ Object Instantiation

Though having things on the stack might be an advantage in terms of allocation and automatic freeing, it has some disadvantages.

  1. You might not want to allocate huge objects on the Stack.

  2. Dynamic dispatch! Consider this code:

#include <iostream>

class A {
public:
  virtual void f();
  virtual ~A() {}
};

class B : public A {
public:
  virtual void f();
};

void A::f() {cout << "A";}
void B::f() {cout << "B";}

int main(void) {
  A *a = new B();
  a->f();
  delete a;
  return 0;
}

This will print "B". Now lets see what happens when using Stack:

int main(void) {
  A a = B();
  a.f();
  return 0;
}

This will print "A", which might not be intuitive to those who are familiar with Java or other object oriented languages. The reason is that you don't have a pointer to an instance of B any longer. Instead, an instance of B is created and copied to a variable of type A.

Some things might happen unintuitively, especially when you are new to C++. In C you have your pointers and that's it. You know how to use them and they do ALWAYS the same. In C++ this is not the case. Just imagine what happens, when you use a in this example as an argument for a method - things get more complicated and it DOES make a huge difference if a is of type A or A* or even A& (call-by-reference). Many combinations are possible and they all behave differently.