Abstract methods do not require implementation

Asked

Viewed 112 times

8

I am doing a job and implemented an abstract method, the case makes a class inherit this, but the compiler does not accuse error for the lack of implementation of the methods. I’m doing it wrong?

class online{
    private:
    public:
        online();
        virtual void build() = 0;
};

class F : public online{
    public:
        F();
};

I’d like the class F be obliged to implement the build.

  • 7

    I think that way F turns out to be an abstract class, doesn’t it? It tries to instantiate an object of hers. I believe that the way to "force" someone to implement the method is to try to instantiate the class.

  • 1

    Are you having some difficulty? Have you tried to do something different than you expected? Say what you need and you’re not being what you want. https://ideone.com/dKoYpc

  • Yes, when I created the object the compiler was in error. Thanks for the help!!

2 answers

1

Your premise is wrong. In C++ there is no way to "force" the implementation of a method (virtual or purely virtual) in a given class in the inheritance chain.

The only rule is that all virtual functions must have an implementation so that this class can be unstable, that is, the compile-time error you are waiting for could only happen if there is an attempt to instantiate that derived class.

Look at that:

class online{
    public:
        virtual void build() = 0;
};

class F : public online{
    public:
        F();
};

int main( void )
{
    F f();  /* Tentando instanciar a classe derivada */
    return 0;
}

Build error:

online.cpp: In function ‘int main()’:
online.cpp:14:4: error: invalid abstract return type for function ‘F f()’
  F f();
    ^
online.cpp:6:7: note:   because the following virtual functions are pure within ‘F’:
 class F : public online{
       ^
online.cpp:3:22: note:  virtual void online::build()
         virtual void build() = 0;

-2

Check the function that will override, this will make the compiler error when trying to instantiate the abstract class. You must use a virtual destructor as well. Try enabling the compiler warnings as well to see if nothing really appears.

class Online {    
public:
    Online() = default;
    virtual ~Online(){}
    virtual void build() = 0;
};

class Foo : public Online{
    public:
        Foo();
        void build() override;
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.