D
D
Daniil Demidko2016-02-16 06:27:50
C++ / C#
Daniil Demidko, 2016-02-16 06:27:50

What's wrong with the word virtual?

I am aware that virtual is not a required keyword and should not affect the override.
But!
Everything is fine with this code:

struct A
{
    /// Слово virtual отсутствует
    std::string Get ()
    {
        return "AB";
    }
};

struct B : public A
{
    /// Переопределяем метод Get
    std::string Get()
    {
        /// Приводим this к A* и вызываем Get, удаляя первый символ
        return ( ( A* ) this ) -> Get () .erase (0, 1); 
    }
};

///...
std :: cout <<B().Get(); /// Все нормально, выводится 'B'

But not with this one:
struct A
{
    /// Слово virtual присутствует
    virtual std::string Get ()
    {
        return "AB";
    }
};

struct B : public A
{
    /// Переопределяем метод Get
    std::string Get()
    {
        /// Приводим this к A* и вызываем Get, удаляя первый символ
        return ( ( A* ) this ) -> Get () .erase (0, 1); 
    }
};

///...
std :: cout <<B().Get(); /// main сразу завершается с возвратом что то около -14556645665566

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2016-02-16
@Daniro_San

std::string Get()
    {
        /// Приводим this к A* и вызываем Get, удаляя первый символ
        return ( ( A* ) this ) -> Get () .erase (0, 1); 
    }

Got infinite recursion because ((A*)this)->Get() is a polymorphic call because Get in class A is defined as virtual. Those. you take from the table of virtual functions of subobject A the pointer to the virtual function Get, and it points to B::Get.
If you want to call a method of class A, just write:
struct B : public A
{
    /// Переопределяем метод Get
    std::string Get()
    {
        return A::Get () .erase (0, 1); 
    }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question