2

I try to learn C++ constructors, Imma noobie yet. I wrote the next class:
screen.h

#ifndef SCREEN_H
#define SCREEN_H

#include "pch.h"

class Screen
{
public:
    Screen(const std::string& name);
    Screen(const Screen& screen);
    Screen(Screen&& screen);

    const std::string& name() const;

    virtual void draw();
private:
    std::string m_name;
};

#endif // SCREEN_H

screen.cpp

#include "screen.h"

Screen::Screen(const std::string& name)
    : m_name{name}
{
    m_name = name;
}

Screen::Screen(const Screen& screen)
    : m_name{screen.m_name}
{

}

Screen::Screen(Screen&& screen)
    : m_name{std::move(screen.m_name)}
{

}

const std::string& Screen::name() const
{
    return this->m_name;
}

But I get an issue in the compilation time:

screen.cpp:4: error: undefined reference to `vtable for Screen'

And so for all constructors.
I can't get that is my mistake... Pls, can anyone explain me?

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123

2 Answers2

5

You must also implement Screen::draw.

In typical implementations, a constructor of a polymorphic class sets up a pointer to the class's "vtable", which contains pointers to the class's virtual functions. Since your first (and only) virtual function is missing, the compiler can't produce this vtable, and so all the constructors complain about it at link time.

aschepler
  • 70,891
  • 9
  • 107
  • 161
4

What aschepler said is absolutely correct. Concerned about your begining, you may want some advice when a virtual function should be used though. Vitual function is used as a method to support polymorphism in cpp, and can be divided into two using scenario.

  1. Interface/ abstract class

    In this scenario, virtual function was declared as pure virtual, with which one class would be called as abstract class and non-instancable. By doing this, you can implement 'interface' like most modern programming support.

    class Interface {
        //....
        virtual void f() = 0;
    };
    class Concrete: public Interface {
        // override this f()
        void f() override {}
    };
    
  2. Polymorphism/ concrete class

    In this scenario, virtual function was declared as normal function except it can be override by derived class. And you must implement it.

    class Parent {
        //...
        virtual void g();
    }
    class Derived: public Parent {
        //...
        void g() override{}
    }
    

Note that you can still declare a function with the same name of parent, which was not declared as virtual function. This would be called hide, and is another topic.

Gustavo Meira
  • 2,875
  • 3
  • 21
  • 33
Frank Wang
  • 788
  • 7
  • 23