Adupa Vasista
Adupa Vasista

Reputation: 83

pure virtual function calling

The first printable(e) is giving "entity" but for the next line, the program crashes. giving some characters. Let me know the error.

#include<iostream>
using namespace std;

class A
{
public:
    virtual string getclassname() = 0;
};

class entity : public A
{
public:
    string getclassname() override
    {
        cout << "entity" << endl;
    }
};

class player : public entity
{
private:
    string m_name2;

public:
    player(const string& name2) // Creating a constructor
        :m_name2(name2) {}

    string getname()
    {
        return m_name2;
    }
public:
    string getclassname() override
    {
        cout << "player" << endl;
    }
};

void printable(A* en)
{
    cout << en->getclassname() << endl;
}

int main()
{
    entity* e = new entity();
    player* p = new player("bird");

    printable(e);
    printable(p);
}

Upvotes: 0

Views: 64

Answers (1)

tadman
tadman

Reputation: 211700

Your getclassname() function doesn't return anything even though it promises it does. This results in undefined behaviour. You should not print, but instead compose a string:

string getclassname() override
{
    return "player";
}

Upvotes: 4

Related Questions