Question 4 (8)#

The Foo Family#

@startuml

interface IFoo {
  + bar()
}

class AFoo {
  + bar()
}
class BFoo {
  + bar()
}

IFoo <|.. AFoo
IFoo <|.. BFoo

@enduml

#pragma once

#include <iostream>

class IFoo
{
public:
    virtual ~IFoo() = default;
    virtual int bar() const = 0;
};

class AFoo : public IFoo
{
public:
    int bar() const override
    {
        std::cout << "AFoo::bar()" << std::endl;
        return 42;
    }
};

class BFoo : public IFoo
{
public:
    BFoo(int i) : _i(i) {}
    int bar() const override
    {
        std::cout << "BFoo::bar()" << std::endl;
        return _i;
    }

private:
    int _i;
};

Usage#

Given the following usage:

#include "the-foos.h"
#include <string>

int main(int argc, char** argv)
{
    std::string the_argument = argv[1];
    IFoo* foo;

    if (the_argument == "a") {
        AFoo a;                                        // <-- lifetime?
        foo = &a;
    }
    else if (the_argument == "b") {
        foo = new BFoo(666);
    }

    std::cout << foo->bar() << std::endl;

    return 0;
}

Which of the following statements is true?

Statement

True

A call as shown will cause undefined behavior

$ ./program a
...?...

Statement

True

A call as shown will cause undefined behavior

$ ./program b
...?...