Search code examples
c++inheritancevirtual

C++ Inheritance virtual function crashing


I have got no idea why this code is crashing, it looks correct to me, but it just crashes with a SIGSEV. I come from Java and am used to "helpful" error messages...

main.cpp

#include <cstdlib>
#include <stdio.h>

#include "DuckV.h"
#include "PenguinV.h" 

bool tryFlyOOP(IBird* birdy)
{
    return birdy->canFly();
}
int main(int argc, char** argv)
{
   DuckV* duckV;
   PenguinV* penguinV;

    printf("My OOP duck %s fly\n", tryFlyOOP(duckV) ? "can" : "can't");
    printf("OOP Penguins %s fly\n", tryFlyOOP(penguinV) ? "can" : "can't");

    return 0;
}

IBird:

#ifndef IBIRD_H
#define IBIRD_H

class IBird
{
public:
    IBird () {}
    virtual bool canFly() {return true;};
};

#endif  /* IBIRD_H */

DuckV/PenguinV are the same besides the name and the return value

#ifndef DUCKV_H
#define DUCKV_H

#include "IBird.h"

class DuckV : public IBird
{
public:
    DuckV(){}
    virtual bool canFly() {return true;}
};

#endif  /* DUCKV_H */

I have tried changing stuff around and I just don't get it. Any help would be greatly appreciated :).


Solution

  • You have not initialized your pointers:

    DuckV* duckV; // points to a random location. No DuckV object exists.
    

    I suggest you drop the pointers and do something like this:

    bool tryFlyOOP(const IBird& birdy)
    {
        return birdy.canFly();
    }
    

    then

    DuckV duckV;
    std::cout << "My OOP duck " << (tryFlyOOP(duckV) ? "can" : "can't") << " fly\n";
    

    This will require that you make your canFly() member function const:

    class IBird
    {
    public:
        IBird () {}
        virtual bool canFly() const {return true;};
    };