views:

113

answers:

4

Will the following program cause any problem during compiling and execution process?

class A{
  public: virtual void foo(){}
};

class B:public A{};

int main(){
    B b;
    b.foo();
}
A: 

Looks fine to me. What problem do you think it causes?

Jon-Eric
@Jon-Eric: I didn't do c++ development for several years and don't remember whether we should do something like `B b = new B()` in cpp?
Roman
That was suprisingly easy to miss. Good catch!
spender
@Roman: In general, you would only use `new` to create an object that needed to exist longer than the current scope. Otherwise, you would create the object on the stack as this question does. It saves you from having to destroy the object yourself, since that happens automatically at the end of the scope. More importantly, it prevents you from leaking memory if you forget to destroy the object, or if you throw an exception between your `new` and `delete`.
Josh Townzen
A: 

Why would it have a problem? You're calling a virtual function that IS defined on the parent class. B inherits it.

Alex
+1  A: 

Maybe, I'm guessing, they were testing if you knew the difference between virtual and abstract?

kervin
Can you explain this in more detail? This is a interview question found on the web, but I don't know the answer.
+1  A: 

There will be no problems compiling or running this program.

virtual functions can be overridden, but they don't have to be. If an object's class does not implement the virtual function, then the superclass will be checked for an implementation.

Paul