-3

In the following example, the class Base is an abstract class. the Derived class inherits from a Base class. I don't override the pure virtual function in derived class. Then, I have been trying to create derived class object, but the compiler gives following error.

error: cannot declare variable 'd' to be of abstract type 'Derived'
     Derived d;

Code here:

#include<iostream>
using namespace std;

class Base
{
public:
    virtual void show() = 0;
};

class Derived : public Base
{

};

int main(void)
{
    Derived d;
    return 0;
}

Why Derived class also become abstract class?

msc
  • 33,420
  • 29
  • 119
  • 214
  • 6
    Yes. The `show` function will be abstract until you define it. – Some programmer dude Jul 19 '17 at 13:29
  • 1
    Why the down-vote? – Stefan Jul 19 '17 at 13:30
  • 2
    I don't feel this question demonstrates any research or thought about the problem. How can `Derived` _not_ be abstract? i.e. if it wasn't, what would happen when someone thinking they had a `Base` tried to call `show()` on it? Nothing good, if somehow the compiler allowed it. – underscore_d Jul 19 '17 at 13:31
  • 3
    @Stefan Not my downvote but your question is "Is Derived class also become abstract class?" and the compiler error message is: "cannot declare variable 'd' to be of abstract type 'Derived'" seems to me like the compiler answered it for you. – Borgleader Jul 19 '17 at 13:31
  • As a sidenote `int main(){ }` is enough. No need for the `void` nor the `return 0;`. – Ron Jul 19 '17 at 13:36
  • 2
    @Ron I would argue that explicitly writing `return 0;` is good style; omitting it is only allowed because so many people couldn't be bothered to type it that the Committee buckled to make such code well-formed, AFAICT. But yes, that's not how to idiomatically write empty argument lists. – underscore_d Jul 19 '17 at 13:37
  • I would imagine any half-decent C++ tutorial/book would cover this. – StoryTeller - Unslander Monica Jul 19 '17 at 13:49

2 Answers2

2

Yes, Derived is an abstract class. This is because there is a pure virtual method show in the Base class that has been inherited by Derived but never resolved. This means that in order for Derived to become a concrete class, you must first implement a show method either in the Base class itself, or in Derived.

aoiee
  • 345
  • 3
  • 15
  • Just a minor quibble over terminology: `Derived` is not "in a way" an abstract class; it simply **is** an abstract class, because it has a pure virtual function that has not been overridden. – Pete Becker Jul 19 '17 at 14:09
2

Yes. A pure virtual function must be implemented in derived classes, or else they remain abstract classes: C++ Virtual/Pure Virtual Explained

Alex
  • 780
  • 4
  • 12