A doubt on abstract base class and pure virtual functions

it is stated that the pure virtual function declared in the base class must be implemented in the derived class else if not implemented the derived class will also become abstract class.why it is and what happens if compiler allows us to create objects for the derived class

please take time and explain with code if possible.

with regards,
vishnu k.
what happens if compiler allows us to create objects for the derived class

It doesn't let you, but you knew that because you typed:

must be implemented in the derived class else if not implemented the derived class will also become abstract class


is this homework?
it is stated that the pure virtual function declared in the base class must be implemented in the derived class else if not implemented the derived class will also become abstract class.why it is


Because it's the only thing that makes sense.

Think about it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Parent
{
public:
    virtual void func() = 0;
};

class Child : public Parent {};

// Both Parent and Child are abstract

int main()
{
    Parent* p = new Child();  // <- this will be a compiler error because you cannot
        // instantiate a Child -- it is abstract.   But assuming this would work...

    p->func();  // <- what function would this call?  Where does the program jump to?
        // there's no body of func() that can be called!
}



When you call a function, the program has to jump somewhere to execute code. If the function is pure virtual and has no body, then the program has nowhere to jump.

Therefore, to prevent this from happening, the most logical approach is to disallow instantiation of abstract objects.
Topic archived. No new replies allowed.